Skip to content

Latest commit

 

History

History
114 lines (82 loc) · 2.42 KB

File metadata and controls

114 lines (82 loc) · 2.42 KB

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)
}

...