题目:
Write a function that takes a string as input and reverse only the vowels of a string. Example 1:
Input: "hello" Output: "holle"Example 2:
Input: "leetcode" Output: "leotcede"Note: The vowels does not include the letter “y”.
解释: 仅仅翻转字符串中的元音字母,用双指针即可,注意,用set()保存元音字母比用list保存元音字母查询速度更快。 注意,python和c++中都无法直接给string[i]赋值,所以需要先转换成数组形式。 python代码:
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels=set("aeiouAEIOU") result=list(s) left,right=0,len(s)-1 while left<right: if (result[left] in vowels) and (result[right] in vowels): result[left],result[right]=result[right],result[left] left+=1 right-=1 else: if result[right] not in vowels: right-=1 if result[left] not in vowels : left+=1 return ''.join(result)c++代码:
#include<set> #include<algorithm> using namespace std; class Solution { public: string reverseVowels(string s) { string vowels="aeiouAEIOU"; set<char> set_vowels(vowels.begin(),vowels.end()); vector<char> list(s.begin(),s.end()); int left=0,right=s.size()-1; while (left<right) { if (set_vowels.find(list[left])!=set_vowels.end() && set_vowels.find(list[right])!=set_vowels.end()) { swap(list[left],list[right]); left++; right--; } else { if (set_vowels.find(list[left])==set_vowels.end()) left++; if (set_vowels.find(list[right])==set_vowels.end()) right--; } } string result=""; //注意是vector<char>转string 不是vector<string>转string result.insert(result.begin(),list.begin(),list.end()); return result; } };总结: stl中学会set.find()