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

leetcode--345--反转字符串中的元音字母

作者: minningl | 来源:发表于2021-01-24 19:01 被阅读0次

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

    示例 1:

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

    输入: "leetcode"
    输出: "leotcede"
    说明:
    元音字母不包含字母"y"。

    链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string

    思路:
    1、定义一个列表ls存储所有的元音字母。
    2、用两个指针分别指向左右端点,如果他们指向的元素是在列表ls中,则将其进行交换,直至左右端点越界

    Python代码:

    class Solution(object):
        def reverseVowels(self, s):
            """
            :type s: str
            :rtype: str
            """
            vowels = ['a','e','i','o','u','A','E','I','O','U']
            ls = list(s)
    
            left = 0
            right = len(ls)-1
    
            while left<right:
                while left<right and s[left] not in vowels:
                    left += 1
                while left<right and s[right] not in vowels:
                    right -= 1
                ls[left],ls[right] = ls[right],ls[left]
                left += 1
                right -= 1
            return ''.join(ls)
    
    

    C++代码:

    class Solution {
    public:
        string reverseVowels(string s) {
            int size=s.size();
            if (size==0) return s;
    
            vector<char> vowels{'a','e','i','o','u','A','E','I','O','U'};
            int left=0;
            int right=size-1;
    
            while (left<right){
                while(left<right && find(vowels.begin(), vowels.end(), s[left])==vowels.end()){
                    left += 1;
                }
                while(left<right && find(vowels.begin(), vowels.end(), s[right])==vowels.end()){
                    right -= 1;
                }
                int temp = s[left];
                s[left] = s[right];
                s[right] = temp;
                left += 1;
                right -= 1;
            }
            return s;
        }
    };
    

    相关文章

      网友评论

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

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