2785. Sort Vowels in a String #2160
-
Topics: Given a 0-indexed string
Return the resulting string. The vowels are Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to permute a given string such that all consonants remain in their original positions, and the vowels are sorted in non-decreasing order of their ASCII values. The vowels include both lowercase and uppercase letters 'a', 'e', 'i', 'o', and 'u'. Approach
Let's implement this solution in PHP: 2785. Sort Vowels in a String <?php
/**
* @param String $s
* @return String
*/
function sortVowels($s) {
$vowels = [];
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$c = $s[$i];
if (isVowel($c)) {
$vowels[] = $c;
}
}
sort($vowels);
$j = 0;
$result = '';
for ($i = 0; $i < $n; $i++) {
$c = $s[$i];
if (isVowel($c)) {
$result .= $vowels[$j++];
} else {
$result .= $c;
}
}
return $result;
}
/**
* @param $c
* @return bool
*/
function isVowel($c) {
return strpos('aeiouAEIOU', $c) !== false;
}
// Test cases
echo sortVowels("lEetcOde") . "\n"; // Output: lEOtcede
echo sortVowels("lYmpH") . "\n"; // Output: lYmpH
?> Explanation:
This approach efficiently ensures that consonants stay in their original positions while vowels are sorted in the required order, leveraging simple string manipulation and sorting techniques. The time complexity is dominated by the sorting step, which is O(m log m) where m is the number of vowels, and the space complexity is O(m) to store the vowels. |
Beta Was this translation helpful? Give feedback.
We need to permute a given string such that all consonants remain in their original positions, and the vowels are sorted in non-decreasing order of their ASCII values. The vowels include both lowercase and uppercase letters 'a', 'e', 'i', 'o', and 'u'.
Approach