描述
Write a function that takes a string as input and reverse only the vowels of a string.
The vowels does not include the letter "y".
您在真实的面试中是否遇到过这个题?
是
样例
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "lintcode", return "lentcodi".
无难度题目,从两边依次推进就好
class Solution {
public:
/**
* @param s: a string
* @return: reverse only the vowels of a string
*/
string reverseVowels(string &s) {
// write your code here
int left = 0, right= s.size() - 1;
while (left < right) {
if (isVowel(s[left]) && isVowel(s[right])) {
swap(s[left++], s[right--]);
} else if (isVowel(s[left])) {
--right;
} else {
++left;
}
}
return s;
}
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
};