- Reverse Vowels of a String
中文English
Write a function that takes a string as input and reverse only the vowels of a string.
Example
Example 1:
Input : s = “hello”
Output : “holle”
Example 2:
Input : s = “lintcode”
Output : “lentcodi”.
Notice
The vowels does not include the letter “y”.
解法1:反向双指针法。
注意:
1)最后的return s; 还是需要。如果input=“u”,没有最后的return s就会出错。
代码如下:
class Solution {
public:
/**
* @param s: a string
* @return: reverse only the vowels of a string
*/
string reverseVowels(string &s) {
int n = s.size();
if (n == 0) return "";
int left = 0, right = n -1;
while(left < right) {
while(!isVowel(s[left]) && (left < right)) left++;
while(!isVowel(s[right]) && (left < right)) right--;
if (left < right) {
swap(s[left], s[right]);
left++; right--;
} else {
return s;
}
}
return s; //This line is still needed!
}
private:
bool isVowel(char c) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}
};