[面试题 17.13][中等][动态规划][前缀树] 恢复空格
题目描述
输入:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
输出: 7
解释: 断句后为"jess looked just like tim her brother",共7个未识别字符。解题思路
最后更新于
输入:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
输出: 7
解释: 断句后为"jess looked just like tim her brother",共7个未识别字符。最后更新于
class Trie:
def __init__(self):
self.root = dict()
def insert(self, word):
root = self.root
for c in word[::-1]:
new_dict = dict()
cur_dict = root.get(c, new_dict)
root[c] = cur_dict
root = cur_dict
def search(self, word):
root = self.root
for c in word[::-1]:
if c not in root:
return False
root = root[c]
return True
class Solution:
def respace(self, dictionary: List[str], sentence: str) -> int:
dic = set(dictionary)
trie = Trie()
for word in dictionary:
trie.insert(word)
n = len(sentence)
if n == 0:
return 0
dp = [0] * n
for i in range(n):
dp[i] = 1 + (dp[i - 1] if i > 0 else 0)
for j in range(i, -1, -1):
t_word = sentence[j: i + 1]
if trie.search(t_word):
if t_word in dic:
dp[i] = min(dp[i], dp[j - 1] if j > 0 else 0)
else:
break
return dp[-1]