class Solution {
//用双指针,一个p1指头,一个p2指尾,从两头开始遍历字符串数组
//p1和p2如果同时是辅音字符,都往中间走
//如果p1的指向元音,p2指向辅音,p2就往中间靠拢直到找到元音进行交换,反之亦然
//结束条件不能是p1=p2;若系统给出的只有两个元音字符,第一次交换字母后,指针交错,两个指针后面会反向行走,超出范围。
bool isOrigin(char c){
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
return true;
else
return false;
}
public:
string reverseVowels(string s) {
int p1=0;
int p2=s.size()-1;
while(p1<p2)
{
if (!isOrigin(s[p1]))
{
p1++;
continue;//执行下一次循环
}
else if(!isOrigin(s[p2]))
{
p2--;
continue;
}
else if(isOrigin(s[p1])&&isOrigin(s[p2]))
{
int temp;
temp=s[p1];
s[p1]=s[p2];
s[p2]=temp;
p1++;
p2--;
}
}
return s;
}
};
反转字符串中的元音字母
最新推荐文章于 2024-07-12 20:18:19 发布