1 Star 0 Fork 332

[]~( ̄ ̄)~* / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.98 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2021-12-24 22:51 . style: format code and docs (#645)

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

English Version

题目描述

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

 

示例 1:

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

示例 2:

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

 

提示:

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

解法

将字符串转为字符数组(或列表),定义双指针 i、j,分别指向数组(列表)头部和尾部,当 i、j 指向的字符均为元音字母时,进行交换。

依次遍历,当 i >= j 时,遍历结束。将字符数组(列表)转为字符串返回即可。

Python3

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
        i, j = 0, len(s) - 1
        chars = list(s)
        while i < j:
            if chars[i] not in vowels:
                i += 1
                continue
            if chars[j] not in vowels:
                j -= 1
                continue
            chars[i], chars[j] = chars[j], chars[i]
            i += 1
            j -= 1
        return ''.join(chars)

Java

class Solution {
    public String reverseVowels(String s) {
        Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        int i = 0, j = s.length() - 1;
        char[] chars = s.toCharArray();
        while (i < j) {
            if (!vowels.contains(chars[i])) {
                ++i;
                continue;
            }
            if (!vowels.contains(chars[j])) {
                --j;
                continue;
            }
            char t = chars[i];
            chars[i] = chars[j];
            chars[j] = t;
            ++i;
            --j;
        }
        return new String(chars);
    }
}

Go

func reverseVowels(s string) string {
	left, right := 0, len(s)-1
	a := []byte(s)
	for left < right {
		for left < right && !isVowel(a[left]) {
			left++
		}
		for left < right && !isVowel(a[right]) {
			right--
		}
		if left != right && isVowel(a[left]) && isVowel(a[right]) {
			a[left], a[right] = a[right], a[left]
			left++
			right--
		}
	}
	return string(a)
}

func isVowel(b byte) bool {
	return b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ||
		b == 'A' || b == 'E' || b == 'I' || b == 'O' || b == 'U'
}

...

Java
1
https://gitee.com/keshuimao/leetcode.git
git@gitee.com:keshuimao/leetcode.git
keshuimao
leetcode
leetcode
main

搜索帮助