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

LeetCode 1410: HTML Entity Parser

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

基本資料
#

難易度: medium 第一次嘗試:2025-07-15

  • 提交紀錄:Wrong Answer → Runtime Error ×2 → Accepted

解題思路
#

由左到右掃,每個位置用 startswith 試六個 entity(String 模板二):

  • 比對到就輸出對應的字元,i 跳過整個 entity。
  • 都沒比對到就輸出原字元,i += 1。

因為輸出的字元不會再被掃描,替換結果不會跟後面的字組成新的 entity。

我的嘗試
#

  1. 第一版用一連串的 replace。">" 應該變成 ">",但 & 換成 & 之後,跟後面的 gt; 組成新的 >,又被換成 >。
  2. 第二、三版改成雙指標往後找 ;,但沒檢查邊界:& 在字串最後時 text[right] 超出範圍,例如 "&" 直接 IndexError。
  3. 加上 right < len(text) 就 AC 了。

正確解法
#

class Solution:
    def entityParser(self, text: str) -> str:
        table = {"&quot;": '"', "&apos;": "'", "&amp;": "&",
                 "&gt;": ">", "&lt;": "<", "&frasl;": "/"}
        out, i = [], 0
        while i < len(text):
            for pattern, ch in table.items():
                if text.startswith(pattern, i):
                    out.append(ch)
                    i += len(pattern)
                    break
            else:
                out.append(text[i])
                i += 1
        return "".join(out)

複雜度
#

時間 O(n · E),E 是 entity 總長(常數),空間 O(n)。

要特別避免的錯誤
#

  • 不要連續 replace,替換出來的字會被下一次替換看到。
  • 往後看之前要檢查邊界;startswith 自己會處理。

面試口說整理
#

我由左到右掃,每個位置試著比對六個 entity,比對到就輸出對應字元並跳過整段,沒有就輸出原字元。輸出的東西不會再被掃描,所以不會有連續 replace 那種「換出來的 & 又組成新 entity」的問題。時間 O(n)。

相關文章

LeetCode 3121: Count the Number of Special Characters II
·1 分鐘
LeetCode Medium Hash-Table String
LeetCode 3121 解題筆記:記錄每個字母小寫最後一次出現和大寫第一次出現的位置,小寫最後一次在大寫第一次之前才算
LeetCode 187: Repeated DNA Sequences
·1 分鐘
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
LeetCode 187 解題筆記:把每個長度 10 的子字串丟進雜湊表計數,出現超過一次的就是答案
LeetCode 208: Implement Trie (Prefix Tree)
·1 分鐘
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 解題筆記:每個節點是 children 字典加一個 is_end 標記;insert、search、startsWith 都是沿著字元往下走
LeetCode 424: Longest Repeating Character Replacement
·1 分鐘
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 解題筆記:可變長度滑動視窗,視窗長度減掉最多的字元次數就是要替換的數量,超過 k 就縮左邊
LeetCode 981: Time Based Key-Value Store
·2 分鐘
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 解題筆記:每個 key 存一個 (timestamp, value) 的 list,timestamp 是遞增的;get 時二分找最後一個 timestamp <= 查詢時間的
LeetCode 49: Group Anagrams
·1 分鐘
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 解題筆記:把每個字串排序後當成 key,同一個 key 的字串就是同一組 anagram