Description

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".

My solution

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方案...

Reference


xufeng
8 声望3 粉丝

有多少人工就有多少智能