1,题目要求
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”.
给定一个字符串,将其中出现的元音字母进行互换,其中包括大小写形式。
2,题目思路
个人的思路,首先是定义一个集合便于查找到元音字母。然后遍历字符串,找到元音字母的index。最后两两交换即可。
但是这种方法时间消耗比较大,因此参考了另一种方法:
这里用到了find_first_of和find_last_of方法,然后交换即可。
3,程序源码
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]);
i++,j--;
}
}
return s;
}
};
其中,函数find_first_of() 查找在字符串中第1个出现的字符c,而函数find_last_of()查找最后
一个出现的c。匹配的位置是返回值。如果没有匹配发生,则函数返回-1。
int find_first_of(char c, int start = 0):
//查找字符串中第1个出现的c,由位置start开始。
//如果有匹配,则返回匹配位置;否则,返回-1.默认情况下,start为0,函数搜索整个字符串。
//find_last_of用法是一样的