3136. 有效单词
3136. 有效单词
题目
A word is considered valid if:
- It contains a minimum of 3 characters.
- It contains only digits (0-9), and English letters (uppercase and lowercase).
- It includes at least one vowel.
- It includes at least one consonant.
You are given a string word.
Return true if word is valid, otherwise, return false.
Notes:
'a','e','i','o','u', and their uppercases are vowels.- A consonant is an English letter that is not a vowel.
Example 1:
Input: word = "234Adas"
Output: true
Explanation:
This word satisfies the conditions.
Example 2:
Input: word = "b3"
Output: false
Explanation:
The length of this word is fewer than 3, and does not have a vowel.
Example 3:
Input: word = "a3$e"
Output: false
Explanation:
This word contains a '$' character and does not have a consonant.
Constraints:
1 <= word.length <= 20wordconsists of English uppercase and lowercase letters, digits,'@','#', and'$'.
题目大意
有效单词 需要满足以下几个条件:
- 至少 包含 3 个字符。
- 由数字 0-9 和英文大小写字母组成。(不必包含所有这类字符。)
- 至少 包含一个 元音字母 。
- 至少 包含一个 辅音字母 。
给你一个字符串 word 。如果 word 是一个有效单词,则返回 true ,否则返回 false 。
注意:
'a'、'e'、'i'、'o'、'u'及其大写形式都属于元音字母 。- 英文中的 辅音字母 是指那些除元音字母之外的字母。
示例 1:
输入: word = "234Adas"
输出: true
解释:
这个单词满足所有条件。
示例 2:
输入: word = "b3"
输出: false
解释:
这个单词的长度少于 3 且没有包含元音字母。
示例 3:
输入: word = "a3$e"
输出: false
解释:
这个单词包含了 '$' 字符且没有包含辅音字母。
提示:
1 <= word.length <= 20word由英文大写和小写字母、数字、'@'、'#'和'$'组成。
解题思路
要判断一个字符串 word 是否是一个有效单词,可以按照以下步骤进行:
- 长度检查:首先检查字符串的长度是否至少为 3 个字符。
- 字符组成检查:使用正则表达式
/[a-zA-Z0-9]/确保字符串只包含数字和字母(包括大小写)。 - 元音和辅音字母检查:遍历字符串,检查每个字符是否为元音或辅音,并设置标志位。
- 返回结果:最终返回是否同时满足元音和辅音的条件。
复杂度分析
- 时间复杂度:
O(n),其中n是字符串的长度,只需遍历一次字符串。 - 空间复杂度:
O(1),使用的额外空间是常量级别,主要是用于存储标志位。
代码
/**
* @param {string} word
* @return {boolean}
*/
var isValid = function (word) {
// 检查长度
if (word.length < 3) return false;
let hasVowels = false,
hasConsonant = false;
for (let char of word) {
// 检查字符是否为有效字符
if (!/[a-zA-Z0-9]/.test(char)) return false;
// 检查元音和辅音
if ('aeiouAEIOU'.indexOf(char) !== -1) {
hasVowels = true;
} else if (/[a-zA-Z]/.test(char)) {
hasConsonant = true;
}
}
// 返回是否满足所有条件
return hasVowels && hasConsonant;
};
