Skip to content

Commit e68da3e

Browse files
Merge pull request #308 from tiennguyen2310/patch-92
Create ValidWord.java
2 parents eb9ab59 + 23e9f25 commit e68da3e

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
3136. Valid Word
3+
Solved
4+
Easy
5+
Topics
6+
premium lock icon
7+
Companies
8+
Hint
9+
A word is considered valid if:
10+
11+
It contains a minimum of 3 characters.
12+
It contains only digits (0-9), and English letters (uppercase and lowercase).
13+
It includes at least one vowel.
14+
It includes at least one consonant.
15+
You are given a string word.
16+
17+
Return true if word is valid, otherwise, return false.
18+
19+
Notes:
20+
21+
'a', 'e', 'i', 'o', 'u', and their uppercases are vowels.
22+
A consonant is an English letter that is not a vowel.
23+
24+
25+
Example 1:
26+
27+
Input: word = "234Adas"
28+
29+
Output: true
30+
31+
Explanation:
32+
33+
This word satisfies the conditions.
34+
35+
Example 2:
36+
37+
Input: word = "b3"
38+
39+
Output: false
40+
41+
Explanation:
42+
43+
The length of this word is fewer than 3, and does not have a vowel.
44+
45+
Example 3:
46+
47+
Input: word = "a3$e"
48+
49+
Output: false
50+
51+
Explanation:
52+
53+
This word contains a '$' character and does not have a consonant.
54+
55+
56+
57+
Constraints:
58+
59+
1 <= word.length <= 20
60+
word consists of English uppercase and lowercase letters, digits, '@', '#', and '$'.
61+
*/
62+
class Solution {
63+
private char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
64+
65+
private boolean isVowel(char c){
66+
for(char v : vowels){
67+
if(v == c)
68+
return true;
69+
}
70+
return false;
71+
}
72+
73+
public boolean isValid(String word) {
74+
if(word.length() < 3)
75+
return false;
76+
77+
int cntvowel = 0, cntconsonant = 0;
78+
for(char c : word.toCharArray()){
79+
if(c >= '0' && c <= '9')
80+
continue;
81+
82+
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
83+
if(isVowel(c))
84+
cntvowel++;
85+
else
86+
cntconsonant++;
87+
}
88+
else
89+
return false;
90+
}
91+
92+
return (cntvowel > 0 && cntconsonant > 0);
93+
}
94+
}

0 commit comments

Comments
 (0)