Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/09/23 18:49), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串894/1554 (看更多)
2707. Extra Characters in a String ## 思路 對dictionary建TrieTree再用recursion dp 不過不用Trie, 直接把dictionary轉成set, 再判斷s[i:j]好像也可以過 ## Code ```python class TrieNode: def __init__(self): self.children = {} self.is_word = False class TrieTree: def __init__(self): self.root = TrieNode() def insert(self, word): curr = self.root for ch in word: if ch not in curr.children: curr.children[ch] = TrieNode() curr = curr.children[ch] curr.is_word = True class Solution: def minExtraChar(self, s: str, dictionary: List[str]) -> int: trie = TrieTree() for word in dictionary: trie.insert(word) n = len(s) @cache def dp(i): if i == n: return 0 # skip res = 1 + dp(i+1) curr = trie.root for j in range(i, n): if s[j] not in curr.children: break curr = curr.children[s[j]] if curr.is_word: res = min(res, dp(j+1)) return res return dp(0) ``` -- https://i.imgur.com/kyBhy6o.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.30.190 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1727088572.A.489.html

09/23 20:00, 1年前 , 1F
大師
09/23 20:00, 1F

09/23 20:22, 1年前 , 2F
大師
09/23 20:22, 2F
文章代碼(AID): #1cyKUyI9 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cyKUyI9 (Marginalman)