一、题意
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".
题意:给定一个字符串,对字符串中含有的元音字母进行反转。
思路:345是在344的基础上做了一个限制,就是只有当两个指针都指向的是元音字符才进行交换。
将元音字母放到一个集合中,方便查找。注意:这里的元音字母包不包含大小写(我在这里没考虑,默认小写结果没通过,集合中是包含了大小写的)
class Solution {
public:
string reverseVowels(string s) {
int left = 0,right = s.length()-1; //对撞指针
vector<char> vecChar={'a','e','i','o','u','A','E','I','O','U'}; //元音字母集合
while(left<right)
{
auto iter = find(vecChar.begin(),vecChar.end(),s[left]); //查找左元素是否是元音
if(iter == vecChar.end())
{
left++; //不是,查找下一个,直到是元音为止
continue;
}
//在这里判断元音的时候,犯了错误。同时判断左右两个指针是否是元音,只要有一个不是元音就++,--,这样是不对的。应该分开考虑
auto iter1 = find(vecChar.begin(),vecChar.end(),s[right]); //查找右元素是否是元音
if(iter1 == vecChar.end())
{
right--; //不是,查找下一个,直到是元音为止
continue;
}
swap(s[left],s[right]);
left++;
right--;
}
return s;
}
};
这里也对比其他的写法,查找自己的不足。效率尽管不如自己的,但是胜在简洁。
fing_first_of的使用方法
string str1("I am change");
string str2("about");
int k=str1.find_first_of(str2); //k返回的值是about这5个字符中任何一个首次在str1中出现的位置;
class Solution {
public:
string reverseVowels(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
i = s.find_first_of("aeiouAEIOU", i); //在字符串s第i个位置开始,查找字符串"aeiouAEIOU"中任意元素出现的位置
j = s.find_last_of("aeiouAEIOU", j);
if (i < j) { //我的代码之所以没有这个判断是因为当前元素不是元音每次都continue重新查询条件
swap(s[i++], s[j--]);
}
}
return s;
}
};