↓快轉到主要內容
  1. LeetCode/

LeetCode 3136: Valid Word

·1 分鐘· ·
LeetCode Easy String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2024-05-05

  • 提交紀錄:Wrong Answer → Accepted → Wrong Answer → Accepted

解題思路
#

四個條件逐一檢查(String 模板四):長度 >= 3、每個字元都是英數字元、至少一個母音(大小寫都算)、至少一個子音。子音是「不是母音的字母」,數字不算。

我的嘗試
#

  • 2024 年第一版把「不是母音」的字元都當成子音,數字也被算成子音:"a3E" 只有母音和數字,答案 False,回傳 True。
  • 2025 年重寫時判斷母音用 w in "aeiou",漏了大寫母音:"bEE" 回傳 False,答案 True。改成 w.lower() 就 AC 了。

正確解法
#

class Solution:
    def isValid(self, word: str) -> bool:
        if len(word) < 3 or not all(c.isalnum() for c in word):
            return False
        vowels = set("aeiouAEIOU")
        has_vowel = any(c in vowels for c in word)
        has_consonant = any(c.isalpha() and c not in vowels for c in word)
        return has_vowel and has_consonant

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 數字不是子音,要確認是字母。
  • 大寫母音也是母音。

面試口說整理
#

我檢查長度至少 3、全部都是英數字元,再確認至少有一個母音和一個子音,子音必須是字母而且不是母音。時間 O(n)。

相關文章

LeetCode 1189: Maximum Number of Balloons
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 1189 解題筆記:每個字母可以組幾個 balloon 是 次數 // 需要數,l 和 o 需要兩個,取最小值
LeetCode 1078: Occurrences After Bigram
·1 分鐘
LeetCode Easy String
LeetCode 1078 解題筆記:切成單字後檢查每個連續三個單字,前兩個符合 first 和 second 就收第三個
LeetCode 1047: Remove All Adjacent Duplicates In String
·1 分鐘
LeetCode Easy String Stack
LeetCode 1047 解題筆記:stack 頂端跟目前字元相同就一起消掉,否則放進 stack;消掉之後新的頂端可能又能跟下一個消
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開
LeetCode 1021: Remove Outermost Parentheses
·1 分鐘
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 解題筆記:用深度計數取代 stack,深度從 0 變 1 的左括號和從 1 變 0 的右括號是外層,其他都保留
LeetCode 929: Unique Email Addresses
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 929 解題筆記:用 @ 切開,只處理 local 的部分(+ 之後丟掉、去掉 .),接回 domain 後放進集合