12ms C++ solution using two pointers


  • 1
    S

    ''' class Solution {
    public:
    string reverseVowels(string s) {

        int start = 0;
        int end = s.size()-1;
        
        while(start<end) {
            if (isVowel(s[start]) && isVowel(s[end])) {
                
                char temp = s[start];
                s[start++] = s[end];
                s[end--] = temp;
                
            }else if (isVowel(s[start])) {
                end--;
            }else if (isVowel(s[end])) {
                start++;
            } else {
                end--;
                start++;
            }
        }
        
        return s;
    }
    
    bool isVowel(char l)
    {
        return (l == 'a' || l == 'A' || l == 'e' || l == 'E' || l == 'i' || l == 'I' || l == 'o' || l == 'O' || l == 'u' || l == 'U');
    }
    

    }; '''

    I know isVowel() is kind of ugly but it turns out runs fast. But I would consider other data structure if the range become wider than 5 vowels.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.