1 minute read

Problem Statement

leetcode problem link

Brute Force [Accepted]

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = {'a','e','i','o','u'}
        lower_s = s.lower()
        l, r = 0, len(s) - 1
        res = list(s)
        while l < r:
            while l < len(s) and lower_s[l] not in vowels:
                l += 1

            while r > l and lower_s[r] not in vowels:
                r -= 1

            if l < r:
                res[l], res[r] = res[r], res[l]
            l += 1
            r -= 1

        return ''.join(res)

Editorial

Approach 1: Two Pointers

class Solution {
public:
    // Return true if the character is a vowel (case-insensitive)
    bool isVowel(char c) {
        return c == 'a' || c == 'i' || c == 'e' || c == 'o' || c == 'u'
            || c == 'A' || c == 'I' || c == 'E' || c == 'O' || c == 'U';
    }

    string reverseVowels(string s) {
        int start = 0;
        int end  = s.size() - 1;

        // While we still have characters to traverse
        while (start < end) {
            // Find the leftmost vowel
            while (start < s.size() && !isVowel(s[start])) {
                start++;
            }
            // Find the rightmost vowel
            while (end >= 0 && !isVowel(s[end])) {
                end--;
            }
            // Swap them if start is left of end
            if (start < end) {
                swap(s[start++], s[end--]);
            }
        }

        return s;
    }
};