Re: [閒聊] 每日leetcode

作者: dont   2024-09-23 18:49:30
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)
```
作者: DJYOSHITAKA (Evans)   2024-09-23 20:00:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com