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

LeetCode 3606: Coupon Code Validator

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

基本資料
#

難易度: easy 第一次嘗試:2025-07-06

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

解題思路
#

兩步:

  1. 過濾:code 非空且只有英數字和底線、類別是四個之一、isActive 是 True。
  2. 排序:先照類別的指定順序,再照 code 的字典序。用 (類別順序, code) 當排序的 key(Hash Table 模板五),類別順序用一個字典查。

我的嘗試
#

版本問題
第一、二版用 range(ord("a"), ord("z")) 判斷字元,不包含 z、Z、9。例如 code = ["9"]:合法,這版回傳空的。第一版也沒排序
第三版範圍修好了,但只照 code 排序,忘了先照類別
第四版排序 key 寫成 (code, 類別),順序反了。例如 code = ["_a", "a"]、類別 ["pharmacy", "grocery"]:答案是 ["a", "_a"],這兩版回傳 ["_a", "a"]
AC改成 (類別, code)

剛好四個類別本身就是字母順序,所以直接用類別字串排序也對;用字典寫明順序比較不依賴巧合。

正確解法
#

class Solution:
    def validateCoupons(self, code: List[str], businessLine: List[str], isActive: List[bool]) -> List[str]:
        order = {"electronics": 0, "grocery": 1, "pharmacy": 2, "restaurant": 3}
        valid = [
            (order[b], c)
            for c, b, active in zip(code, businessLine, isActive)
            if active and b in order and c and all(ch.isalnum() or ch == "_" for ch in c)
        ]
        return [c for _, c in sorted(valid)]

str.isalnum() 對非 ASCII 的字母也會回傳 True,這題的輸入只有 ASCII 所以沒問題。

複雜度
#

時間 O(L + n log n),L 是所有 code 的總長度,空間 O(n)。

要特別避免的錯誤
#

  • range(a, b) 不包含 b。
  • 多條件排序時,key 的順序就是優先順序。

面試口說整理
#

我先過濾出合法的優惠券:code 非空而且只有英數字和底線、類別在清單裡、狀態是啟用。再用(類別順序, code)排序,類別順序用字典查。時間 O(n log n)。

相關文章

LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個
LeetCode 242: Valid Anagram
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 242 解題筆記:兩個字串的字元次數完全相同就是 anagram,用 Counter 比較或排序後比較
LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 分鐘
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 解題筆記:要減少種類就得整種刪掉,從出現次數最少的開始刪
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 分鐘
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 解題筆記:每次操作會讓最小的正數那一群變成 0,所以次數就是不同的正數有幾種
LeetCode 49: Group Anagrams
·1 分鐘
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 解題筆記:把每個字串排序後當成 key,同一個 key 的字串就是同一組 anagram