题目:
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".
分析:
代码:
class Solution {
public:
string reverseVowels(string s) {
int len = s.length();
if (len < 2)return s;
string t(len, ' ');
int pre = 0, end = len - 1;
while (pre < end) {
while (pre < end&&!isVowel(s[pre])) {
t[pre] = s[pre];
pre++;
}
while (pre < end&&!isVowel(s[end])) {
t[end] = s[end];
end--;
}
if (pre < end&&isVowel(s[end]) && isVowel(s[pre])) {
t[pre] = s[end];
t[end] = s[pre];
++pre;
--end;
}
}
if (pre == end)t[pre] = s[pre];
return t;
}
bool isVowel(char c) {
return tolower(c) == 'a' || tolower(c) == 'i' || tolower(c) == 'o' || tolower(c) == 'e' || tolower(c) == 'u' ;
}
};