反转字符串中的元音字符:分别设置一个首尾指针,逐步移动,当首尾指针均为元音字符时,交换位置即可;
class Solution {
public:
string reverseVowels(string s) {
int begin=0,end=s.length()-1;
while(begin<end)
{
if(isVowel(s[begin])&&isVowel(s[end]))
{
char temp=s[begin];
s[begin]=s[end];
s[end]=temp;
begin++;
end--;
}
else
{
if(!isVowel(s[begin]))
begin++;
if(!isVowel(s[end]))
end--;
}
}
return s;
}
bool isVowel(char c)
{
if(tolower(c)=='a'||tolower(c)=='e'||tolower(c)=='i'||tolower(c)=='o'||tolower(c)=='u')
return 1;
else
return 0;
}
};
本文介绍了一种使用双指针技术来反转字符串中元音字母的方法。通过定义开始和结束指针,逐步向中间靠拢,当两端都是元音时进行交换。此方法适用于多种编程任务。
532

被折叠的 条评论
为什么被折叠?



