Skip to content

3136. Valid Word

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  bool isValid(string word) {
    return word.length() >= 3 &&
           ranges::all_of(word, [](char c) { return isalnum(c); }) &&
           ranges::any_of(word, isVowel) && ranges::any_of(word, isConsonant);
  }

 private:
  static bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiouAEIOU";
    return kVowels.find(c) != string_view::npos;
  }

  static bool isConsonant(char c) {
    return isalpha(c) && !isVowel(c);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public boolean isValid(String word) {
    return word.length() >= 3 && word.chars().allMatch(Character::isLetterOrDigit) &&
        word.chars().anyMatch(c -> isVowel((char) c)) &&
        word.chars().anyMatch(c -> isConsonant((char) c));
  }

  private boolean isVowel(char c) {
    return "aeiouAEIOU".indexOf(c) != -1;
  }

  private boolean isConsonant(char c) {
    return Character.isLetter(c) && !isVowel(c);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def isValid(self, word: str) -> bool:
    kVowels = 'aeiouAEIOU'

    def isConsonant(c: str) -> bool:
      return c.isalpha() and c not in kVowels

    return (len(word) >= 3 and
            all(c.isalnum() for c in word) and
            any(c in kVowels for c in word) and
            any(isConsonant(c) for c in word))