leetcode Reverse Vowels of a String 反转字符串中的母音
一、学习要点:
1.find_first_of:查找与字符串str中某个字符相同的位置,并返回他的第一个出现的位置,如果没有返回string::npos;即最后一个字符的后面一个位置;
2.find_last_of:从后往前匹配;
二、代码:
#include<stdlib.h>
#include<stdio.h>
#include<string>
using namespace std;
class Solution
{
public:
string reverseVowels(string s)
{
int i = 0;
int j = s.size() - 1;
string temp = "aoeiuAOEIU";
while (i < j) {
i = s.find_first_of(temp, i);
j = s.find_last_of(temp, j);
if (i < j) {
swap(s[i++], s[j--]);
}
}
return s;
}
};
int main()
{
string s = "hello";
string s1;
Solution ob;
s1 = ob.reverseVowels(s);
for (string::iterator iter = s1.begin(); iter != s1.end(); iter++)
{
printf("%c",*iter);
}
system("pause");
return 0;
}
三、运行结果: