Skip to content

2785. Sort Vowels in a String 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  string sortVowels(string s) {
    string ans;
    vector<char> vowels;

    for (const char c : s)
      if (isVowel(c))
        vowels.push_back(c);

    ranges::sort(vowels);

    int i = 0;  // vowels' index
    for (const char c : s)
      ans += isVowel(c) ? vowels[i++] : c;

    return ans;
  }

 private:
  bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiouAEIOU";
    return kVowels.find(c) != string_view::npos;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public String sortVowels(String s) {
    StringBuilder sb = new StringBuilder();
    List<Character> vowels = new ArrayList<>();

    for (final char c : s.toCharArray())
      if (isVowel(c))
        vowels.add(c);

    Collections.sort(vowels);

    int i = 0; // vowels' index
    for (final char c : s.toCharArray())
      sb.append(isVowel(c) ? vowels.get(i++) : c);

    return sb.toString();
  }

  private boolean isVowel(char c) {
    return "aeiouAEIOU".indexOf(c) != -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def sortVowels(self, s: str) -> str:
    kVowels = 'aeiouAEIOU'
    ans = []
    vowels = sorted([c for c in s if c in kVowels])

    i = 0  # vowels' index
    for c in s:
      if c in kVowels:
        ans.append(vowels[i])
        i += 1
      else:
        ans.append(c)

    return ''.join(ans)