美文网首页
Leetcode 345. 反转字符串中的元音字母

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

作者: LonnieQ | 来源:发表于2019-11-16 19:05 被阅读0次

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

    示例 1:

    输入: "hello"
    输出: "holle"
    

    示例 2:

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

    说明:
    元音字母不包含字母"y"。

    C++代码

    #include <iostream>
    #include <vector>
    #include <map>
    #include <set>
    using namespace std;
    class Solution {
    public:
        bool isVowel(char c) {
            c = tolower(c);
            return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
        }
        string reverseVowels(string s) {
            int i = 0, j = (int)s.size() - 1;
            while (i < j) {
                while (i < j && !isVowel(s[i])) ++i;
                while (i < j && !isVowel(s[j])) --j;
                if (i < j) swap(s[i++], s[j--]);
            }
            return s;
        }
    };
    int main(int argc, const char * argv[]) {
        Solution solution;
        cout << solution.reverseVowels("hello") << endl;
        cout << solution.reverseVowels("leetcode") << endl;
        return 0;
    }
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string

    相关文章

      网友评论

          本文标题:Leetcode 345. 反转字符串中的元音字母

          本文链接:https://www.haomeiwen.com/subject/oazyictx.html