[LeetCode 3136] Valid Word
LeetCode 3136 (Java)
[Valid Word] 문제 풀이
[LeetCode 3136] Valid Word
Description
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.
- This word contains a
Constraints
1 <= word.length <= 20wordconsists of English uppercase and lowercase letters, digits,'@','#', and'$'.
Hint
Hint 1
Use if-else to check all the conditions.
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public boolean isValid(String word) {
if (word.length() < 3) {
return false;
}
boolean hasVowel = false, hasConsonant = false;
boolean[] vs = new boolean[26];
for (char c : "aeiou".toCharArray()) {
vs[c - 'a'] = true;
}
for (char c : word.toCharArray()) {
if (Character.isAlphabetic(c)) {
if (vs[Character.toLowerCase(c) - 'a']) {
hasVowel = true;
} else {
hasConsonant = true;
}
} else if (!Character.isDigit(c)) {
return false;
}
}
return hasVowel && hasConsonant;
}
}
| Runtime | Memory |
|---|---|
| 1 ms | 42.1 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public boolean isValid(String word) {
Set<Character> vowels = Set.of('a','e','i','o','u','A','E','I','O','U');
int vowelsNum = 0, consNum = 0;
if(word.length() < 3)return false;
for(char c:word.toCharArray()){
if(!Character.isLetterOrDigit(c))return false;
if(Character.isLetter(c)){
if(vowels.contains(c))vowelsNum++;
else if(!vowels.contains(c))consNum++;
}
}
return vowelsNum > 0 && consNum > 0;
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/3100-3199/3136.Valid%20Word/Solution.java
This post is licensed under CC BY 4.0 by the author.
