[LeetCode] 3136. Valid Word

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 <= 20
word consists of English uppercase and lowercase letters, digits, '@', '#', and '$'.

有效单词。

有效单词 需要满足以下几个条件:

至少 包含 3 个字符。
由数字 0-9 和英文大小写字母组成。(不必包含所有这类字符。)
至少 包含一个 元音字母 。
至少 包含一个 辅音字母 。
给你一个字符串 word 。如果 word 是一个有效单词,则返回 true ,否则返回 false 。

注意:
'a'、'e'、'i'、'o'、'u' 及其大写形式都属于 元音字母 。
英文中的 辅音字母 是指那些除元音字母之外的字母。

思路

这道题不涉及算法,按规则判断即可。

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {
    public boolean isValid(String word) {
        if (word.length() < 3) {
            return false;
        }
        boolean hasVowel = false;
        boolean hasConsonant = false;
        for (char c : word.toCharArray()) {
            if (Character.isLetterOrDigit(c)) {
                if (Character.isLetter(c)) {
                    char lowerC = Character.toLowerCase(c);
                    if ("aeiou".indexOf(lowerC) >= 0) {
                        hasVowel = true;
                    } else {
                        hasConsonant = true;
                    }
                }
            } else {
                // Invalid character (not a digit or letter)
                return false;
            }
        }
        return hasVowel && hasConsonant;
    }
}
posted @ 2025-07-15 09:15  CNoodle  阅读(36)  评论(0)    收藏  举报