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.
LeetCode Problem - 3136
class Solution {
// Method to check if a word is valid based on the presence of vowels and consonants
public boolean isValid(String word) {
// If the word length is less than 3, it's invalid
if (word.length() < 3) {
return false;
}
// Initialize counts for vowels and consonants
int vowelCount = 0;
int consonantCount = 0;
// Iterate through each character of the word
for (char ch : word.toCharArray()) {
// If the character is not a letter or digit, the word is invalid
if (!Character.isLetterOrDigit(ch)) {
return false;
}
// If the character is a vowel, increment the vowel count
if ("aeiouAEIOU".indexOf(ch) != -1) {
vowelCount++;
}
// If the character is a consonant, increment the consonant count
else if ((ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') && "aeiouAEIOU".indexOf(ch) == -1) {
consonantCount++;
}
}
// The word is valid if it contains at least one vowel and one consonant
return vowelCount > 0 && consonantCount > 0;
}
}