天天看點

Leetcode(java,python題解):345.反轉字元串中的元音字元

Leetcode:345.反轉字元串中的元音字元

題目描述

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

編寫一個函數,以字元串作為輸入,反轉該字元串中的元音字母。

示例 1:

輸入: “hello”

輸出: “holle”

示例 2:

輸入: “leetcode”

輸出: “leotcede”

說明:

元音字母不包含字母"y"。

解題思路

使用雙指針,一個從頭到尾周遊,一個從尾到頭周遊。

遇到元音字元交換,否則不交換。

java代碼

class Solution {
    private final static HashSet<Character> vowels = new HashSet<>(
        Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));

    public String reverseVowels(String s) {
        int i = 0, j = s.length() - 1;
        char[] result = new char[s.length()];
        while(i <= j){
            char ci = s.charAt(i);
            char cj = s.charAt(j);
            if(!vowels.contains(ci))
                result[i++] = ci;
            else if(!vowels.contains(cj))
                result[j--] = cj;
            else{
                result[i++] = cj;
                result[j--] = ci;
            }
        }
        return new String(result);
    }
}
           

python代碼

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        #str是不可變類型,化為list可變類型
        t = list(s)
        i , j = 0, len(s) - 1
        while i <= j:
            if t[i] not in vowels:
                i += 1
                continue
            elif t[j] not in vowels:
                j -= 1
                continue
            else:
                t[i], t[j] = t[j], t[i]
                i += 1
                j -= 1
        return "".join(t)
           

本文參考自CyC2018的GitHub項目更多内容通路如下連結

https://github.com/CyC2018/CS-Notes