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”.
Note:
The vowels does not include the letter “y”.
解答:
一刷时没有写思路,二刷的代码如下,值得注意的是,
可以使用swap交换string中两个字母的值。这就很方便了。
class Solution {
public:
string reverseVowels(string s) {
int i=0,j=s.size()-1;
while(i<j)
{
while((s[i]!='a'&&s[i]!='e'&&s[i]!='i'&&s[i]!='o'&&s[i]!='u'&&s[i]!='A'&&s[i]!='E'&&s[i]!='I'&&s[i]!='O'&&s[i]!='U')&&i<j)
i++;
while((s[j]!='a'&&s[j]!='e'&&s[j]!='i'&&s[j]!='o'&&s[j]!='u'&&s[j]!='A'&&s[j]!='E'&&s[j]!='I'&&s[j]!='O'&&s[j]!='U')&&i<j)
j--;
swap(s[i],s[j]);
i++;
j--;
}
return s;
}
};