Write a function that takes a string as input and reverse only the vowels of a string.python
Example 1:
Given s = "hello", return "holle".segmentfault
Example 2:
Given s = "leetcode", return "leotcede".函數
Note:
The vowels does not include the letter "y".指針
class Solution { public: string reverseVowels(string s) { int i=0,j=s.size()-1; while(i<j){ while(!isaeiou(s[i])) ++i; while(!isaeiou(s[j])) --j; if(i>=j) break; swap(s[i++],s[j--]); } return s; } private: bool isaeiou(char c){ return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U'; } };
思路和第344題一致, 忽略掉非aeiou的元素便可, 實現方式也是採用雙指針, 借鑑於leetcode 344中優秀答案. 只不過本身寫的這個判斷是否爲aeiou的函數有點醜...仍是須要專門學一下C++語法+STL之類的,腦海中只會python的dict或者set方案...code