LeetCode #345 Reverse Vowels of a String 反转字符串中的元音字母

345 Reverse Vowels of a String 反转字符串中的元音字母

Description:
Write a function that takes a string as input and reverse only the vowels of a string.

Example :

Example 1:
Input: "hello"
Output: "holle"

Example 2:
Input: "leetcode"
Output: "leotcede"

Note:
The vowels does not include the letter "y".

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

示例 :

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

示例 2:
输入: "leetcode"
输出: "leotcede"

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

思路:

双指针循环交换, 判断是否是元音字母即可
时间复杂度O(n), 空间复杂度O(1)

代码:
C++:

class Solution 
{
public:
    string reverseVowels(string s) 
    {
        int i = 0, j = s.size() - 1;
        string vowel = "aeiouAEIOU";
        while (i < j) 
        {
            while (vowel.find(s[i]) == -1 and i < j) i++;
            while (vowel.find(s[j]) == -1 and i < j) j--;
            swap(s[i++], s[j--]);
        }
        return s;
    }
};

Java:

class Solution {
    public String reverseVowels(String s) {
        int i = 0, j = s.length() - 1;
        char[] c = s.toCharArray();
        String vowel = "aeiouAEIOU";
        while (i < j) {
            while (i < j && vowel.indexOf(c[i]) == -1) i++;
            while (i < j && vowel.indexOf(c[j]) == -1) j--;   
            if (i < j) {
                c[i] ^= c[j];
                c[j] ^= c[i];
                c[i++] ^= c[j--];                
            }
        }
        return new String(c);
    }
}

Python:

class Solution:
    def reverseVowels(self, s: str) -> str:
        i, j, s, vowel = 0, len(s) - 1, list(s), ('a', 'e', 'i', 'o', 'u')
        while i < j:
            while not s[i].lower() in vowel and i < j:
                i += 1
            while not s[j].lower() in vowel and i < j:
                j -= 1
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1
        return ''.join(s)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容