345. Reverse Vowels of a String(python+cpp)
阿新 • • 發佈:2018-11-03
題目:
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()