题目:

示例:

分析:
给一个字符串,将里面的元音字母反转,并且保持非元音字母不变(包括顺序).
字符串反转类型的题,我们都可以使用双指针来解决:定义首尾指针,分别向中间靠拢,直到首尾指针都指向了元音字母,然后交换首尾指针所指的字母,如此不会影响到非元音字母,同时也将元音字母反转了.


代码+结果如下:
cpp
class Solution {
public:
//判断是否为元音字母
bool isY(char c){
if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U'){
return true;
}
return false;
}
string reverseVowels(string s) {
int l=0;
int r=s.size()-1;
//双指针寻找首尾元音字母
while(l<r){
while(l<r&&!isY(s[l])) ++l; //左指针向右寻找元音字母
while(l<r&&!isY(s[r])) --r; //右指针向左寻找元音字母
char temp=s[l];
s[l]=s[r];s[r]=temp;
++l;--r;
}
return s;
}
};
