Wednesday, May 25, 2016

Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Subscribe to see which companies asked this question

Sol:

class Solution {
public:
    string reverseVowels(string s) {
        if (s.size() < 2)
            return s;
        int start = 0, end = s.size() - 1;
        while (1) {
            if (isVowel(s[start++])) {
                while (end >= (start - 1) && !isVowel(s[end--]));
                if (end < (start - 1))
                  return s;
                char temp = s[start - 1];
                s[start - 1] = s[end + 1];
                s[end + 1] = temp;
            }
        }
        return s;
    }
    bool isVowel(char c) {
        switch(c) {
            case 'a':
            case 'A':
              return true;
            case 'e':
            case 'E':
              return true;
            case 'i':
            case 'I':
              return true;
            case 'o':
            case 'O':
              return true;
            case 'u':
            case 'U':
              return true;
        }
        return false;
    }
};

No comments:

Post a Comment