# 345. Reverse Vowels of a String

• Time: $O(n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { public: string reverseVowels(string s) { int l = 0; int r = s.length() - 1; while (l < r) { while (l < r && !isVowel(s[l])) ++l; while (l < r && !isVowel(s[r])) --r; swap(s[l++], s[r--]); } return s; } 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 class Solution { public String reverseVowels(String s) { final String kVowels = "aeiouAEIOU"; StringBuilder sb = new StringBuilder(s); int l = 0; int r = s.length() - 1; while (l < r) { while (l < r && !kVowels.contains("" + sb.charAt(l))) ++l; while (l < r && !kVowels.contains("" + sb.charAt(r))) --r; sb.setCharAt(l, s.charAt(r)); sb.setCharAt(r, s.charAt(l)); ++l; --r; } return sb.toString(); } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution: def reverseVowels(self, s: str) -> str: chars = list(s) kVowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} l = 0 r = len(s) - 1 while l < r: while l < r and chars[l] not in kVowels: l += 1 while l < r and chars[r] not in kVowels: r -= 1 chars[l], chars[r] = chars[r], chars[l] l += 1 r -= 1 return ''.join(chars)