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

示例 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;
    }
};

相关文章:

  • 2022-01-14
  • 2021-06-25
  • 2022-01-22
  • 2021-07-08
  • 2022-12-23
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-26
  • 2021-05-28
  • 2021-08-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案