|
| 1 | +# 2785. Sort Vowels in a String |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: String, Sorting. |
| 5 | +- Similar Questions: Reverse Vowels of a String. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given a **0-indexed** string `s`, **permute** `s` to get a new string `t` such that: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +- All consonants remain in their original places. More formally, if there is an index `i` with `0 <= i < s.length` such that `s[i]` is a consonant, then `t[i] = s[i]`. |
| 14 | + |
| 15 | +- The vowels must be sorted in the **nondecreasing** order of their **ASCII** values. More formally, for pairs of indices `i`, `j` with `0 <= i < j < s.length` such that `s[i]` and `s[j]` are vowels, then `t[i]` must not have a higher ASCII value than `t[j]`. |
| 16 | + |
| 17 | + |
| 18 | +Return **the resulting string**. |
| 19 | + |
| 20 | +The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. |
| 21 | + |
| 22 | + |
| 23 | +Example 1: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: s = "lEetcOde" |
| 27 | +Output: "lEOtcede" |
| 28 | +Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places. |
| 29 | +``` |
| 30 | + |
| 31 | +Example 2: |
| 32 | + |
| 33 | +``` |
| 34 | +Input: s = "lYmpH" |
| 35 | +Output: "lYmpH" |
| 36 | +Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH". |
| 37 | +``` |
| 38 | + |
| 39 | + |
| 40 | +**Constraints:** |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +- `1 <= s.length <= 105` |
| 45 | + |
| 46 | +- `s` consists only of letters of the English alphabet in **uppercase and lowercase**. |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +## Solution |
| 51 | + |
| 52 | +```javascript |
| 53 | +/** |
| 54 | + * @param {string} s |
| 55 | + * @return {string} |
| 56 | + */ |
| 57 | +var sortVowels = function(s) { |
| 58 | + var vowels = s.split('') |
| 59 | + .filter(isVowels) |
| 60 | + .sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)); |
| 61 | + var res = ''; |
| 62 | + var index = 0; |
| 63 | + for (var i = 0; i < s.length; i++) { |
| 64 | + if (isVowels(s[i])) { |
| 65 | + res += vowels[index++]; |
| 66 | + } else { |
| 67 | + res += s[i]; |
| 68 | + } |
| 69 | + } |
| 70 | + return res; |
| 71 | +}; |
| 72 | + |
| 73 | +var isVowels = function(char) { |
| 74 | + var chars = ['a', 'e', 'i', 'o', 'u']; |
| 75 | + return chars.includes(char.toLowerCase()) || chars.includes(char.toUpperCase()); |
| 76 | +}; |
| 77 | +``` |
| 78 | + |
| 79 | +**Explain:** |
| 80 | + |
| 81 | +nope. |
| 82 | + |
| 83 | +**Complexity:** |
| 84 | + |
| 85 | +* Time complexity : O(n * log(n)). |
| 86 | +* Space complexity : O(n). |
0 commit comments