345. Reverse Vowels of a String(python+cpp)
生活随笔
收集整理的這篇文章主要介紹了
345. Reverse Vowels of a String(python+cpp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Example 2:
Input: "leetcode" Output: "leotcede"Note: The vowels does not include the letter “y”.
解釋:
僅僅翻轉字符串中的元音字母,用雙指針即可,注意,用set()保存元音字母比用list保存元音字母查詢速度更快。
注意,python和c++中都無法直接給string[i]賦值,所以需要先轉換成數組形式。
python代碼:
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>轉stringresult.insert(result.begin(),list.begin(),list.end());return result;} };總結:
stl中學會set.find()
總結
以上是生活随笔為你收集整理的345. Reverse Vowels of a String(python+cpp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3 tkinter电子书_P
- 下一篇: python倒三角形粉色填充笔的形状海龟