Skip to content

Latest commit

 

History

History
130 lines (96 loc) · 2.69 KB

File metadata and controls

130 lines (96 loc) · 2.69 KB
comments difficulty edit_url rating source tags
true
简单
1232
第 4 场双周赛 Q2
字符串

English Version

题目描述

给你一个字符串 s ,请你删去其中的所有元音字母 'a''e''i''o''u',并返回这个新字符串。

 

示例 1:

输入:s = "leetcodeisacommunityforcoders"
输出:"ltcdscmmntyfrcdrs"

示例 2:

输入:s = "aeiou"
输出:""

 

提示:

  • 1 <= S.length <= 1000
  • s 仅由小写英文字母组成

解法

方法一:模拟

我们直接按照题目要求,遍历字符串,将不是元音字母的字符拼接到结果字符串中即可。

时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。忽略答案字符串的空间消耗,空间复杂度 $O(1)$

Python3

class Solution:
    def removeVowels(self, s: str) -> str:
        return "".join(c for c in s if c not in "aeiou")

Java

class Solution {
    public String removeVowels(String s) {
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')) {
                ans.append(c);
            }
        }
        return ans.toString();
    }
}

C++

class Solution {
public:
    string removeVowels(string s) {
        string ans;
        for (char& c : s) {
            if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')) {
                ans += c;
            }
        }
        return ans;
    }
};

Go

func removeVowels(s string) string {
	ans := []rune{}
	for _, c := range s {
		if !(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
			ans = append(ans, c)
		}
	}
	return string(ans)
}

TypeScript

function removeVowels(s: string): string {
    return s.replace(/[aeiou]/g, '');
}