您的位置:首页 > 其它

leetcode Reverse Vowels of a String 反转字符串中的母音

2017-10-01 14:46 866 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: