LeetCode Solutions

345. Reverse Vowels of a String

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  string reverseVowels(string s) {
    const unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u',
                                     'A', 'E', 'I', 'O', 'U'};
    int l = 0;
    int r = s.length() - 1;

    while (l < r) {
      while (l < r && !vowels.count(s[l]))
        ++l;
      while (l < r && !vowels.count(s[r]))
        --r;
      swap(s[l++], s[r--]);
    }

    return s;
  }
};
			

class Solution {
  public String reverseVowels(String s) {
    final String vowels = "aeiouAEIOU";
    StringBuilder sb = new StringBuilder(s);
    int l = 0;
    int r = s.length() - 1;

    while (l < r) {
      while (l < r && !vowels.contains("" + sb.charAt(l)))
        ++l;
      while (l < r && !vowels.contains("" + sb.charAt(r)))
        --r;
      sb.setCharAt(l, s.charAt(r));
      sb.setCharAt(r, s.charAt(l));
      ++l;
      --r;
    }

    return sb.toString();
  }
}
			

class Solution:
  def reverseVowels(self, s: str) -> str:
    charList = list(s)
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    l = 0
    r = len(s) - 1

    while l < r:
      while l < r and charList[l] not in vowels:
        l += 1
      while l < r and charList[r] not in vowels:
        r -= 1
      charList[l], charList[r] = charList[r], charList[l]
      l += 1
      r -= 1

    return ''.join(charList)