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”.
题意:反转字母母音,第一个和最后一个互换,第二个和倒数第二个互换,依次类推。
思路:使用find_first_of 和find_last_of,find_first_of查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,如果没找到就返回string::npos 。
class Solution {
public:
string reverseVowels(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
i = s.find_first_of("aeiouAEIOU", i);
j = s.find_last_of("aeiouAEIOU", j);
if(i < j) {
swap(s[i++], s[j--]);
}
}
return s;
}
};