[Leetcode] 36. Valid Word

whitehousechef·2025년 7월 15일

https://leetcode.com/problems/valid-word/solutions/5113672/easy-video-solution-how-to-in-interview-conditional-statements/?envType=daily-question&envId=2025-07-15

initial

v easy question but my code have been more succinct

in string there is .alpha() to check if it is alphabet and .isdigit() to check if it is a digit. I could have used that instead of converting the alphabets to ascii value

initial that works

class Solution:
    def isValid(self, word: str) -> bool:
        vowel_check=False
        consonant_check=False
        vowel=set({'a','e','i','o','u','A','E','I','O','U'})
        for i in word:
            if i in vowel:
                vowel_check=True
            elif 0<=ord(i)-ord('a')<26 or 0<=ord(i)-ord('A')<26:
                consonant_check=True
            elif not i.isalnum():
                    return False
        if vowel_check and consonant_check and len(word)>=3:
            return True
        else:
            return False

sol

more succinct

class Solution:
    def isValid(self, s):
        if len(s) < 3:
            return False
        
        vowels = 0
        consonants = 0
        
        for c in s:
            if c.isalpha():
                if c.lower() in 'aeiou':
                    vowels += 1
                else:
                    consonants += 1
            elif not c.isdigit():
                return False  # Invalid character if not a letter or digit
        
        return vowels >= 1 and consonants >= 1

complexity

n time
1 space

0개의 댓글