345. 反转字符串中的元音字母

题目:编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:

输入:"hello"
输出:"holle"
示例 2:

输入:"leetcode"
输出:"leotcede"

1.原创

class Solution {
public:
    string reverseVowels(string s) {
        int n = s.length();
        if (n<1)
            return s;
        else{
            int i =0;
            int j = n-1;
            string yuan = "aeiouAEIOU";
            for(int i=0,j=n-1;i<j;++i,--j){
                while((yuan.find(s[i],0))==string::npos &&i<j)
                    i++;
                while((yuan.find(s[j],0))==string::npos &&i<j)
                    j--;
                if(i<j)
                    swap(s[i],s[j]);
                else
                    break;
            }
            return s;
        }
    }
};

2.题解

class Solution {
private:
    set<char> dict={'a','o','e','i','u','A','O','E','I','U'};
public:
    // 题解:首尾指针,类比快排代码
    string reverseVowels(string& s) {
        int i=0,j=s.size()-1;
        while(i<j)
        {
            while(!dict.count(s[i])&&i<j)i++;
            while(!dict.count(s[j])&&i<j)j--;
            if(i<j)swap(s[i++],s[j--]);
        }
        return s;
    }
};
posted @ 2021-03-04 18:21  USTC丶ZCC  阅读(71)  评论(0编辑  收藏  举报