成了小写。像句子"I reset the computer. It still didn’t boot!"已经变成了"iresetthecomputeritstilldidntboot"。在处理标点符号和大小写之前,你得先把它断成词语。当然了,你有一本厚厚的词典dictionary,不过,有些词没在词典里。假设文章用sentence表示,设计一个算法,把文章断开,要求未识别的字符最少,返回未识别的字符数。
注意:本题相对原题稍作改动,只需返回未识别的字符数
示例:
输入:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
输出: 7
解释: 断句后为"jess looked just like tim her brother",共7个未识别字符。
提示:
0 <= len(sentence) <= 1000
dictionary中总字符数不超过 150000。
你可以认为dictionary和sentence中只包含小写字母。
一、动态规划
当第 i 个字符无法与前面任何一个子串组成单词时,则第 i 个字符将算作一个未识别字符:dp[i] = dp[i - 1] + 1;
当第 i 个字符可以与前面某个子串组成单词时,j 的取值需要从 0 遍历到 i - 1。当 sentence[j:i] 能够组成单词,所以它对未识别字符数没有任何贡献,只需要考虑 sentence[:j] 这一部分子串的最少未识别字符数即可,它对应的状态是 f[j]。
class Solution:
def respace(self, dictionary: List[str], sentence: str) -> int:
d = {}.fromkeys(dictionary)
n = len(sentence)
f = [0]*(n+1)
for i in range(1, n+1):
f[i] = f[i-1] + 1
for j in range(i):
if sentence[j:i] in d:
f[i] = min(f[i], f[j])
return f[-1]
二、字典法
class TreeNode:
def __init__(self):
self.child = {}
self.is_word = 0
class Solution:
def tree(self, dictionary):
for word in dictionary:
node = self.root
for s in word:
if not s in node.child:
node.child[s] = TreeNode()
node = node.child[s]
node.is_word = 1
def respace(self, dictionary: List[str], sentence: str) -> int:
self.root = TreeNode()
self.tree(dictionary)
n = len(sentence)
dp = [0] * (n+1)
for i in range(n-1, -1, -1):
dp[i] = n-i
node = self.root
for j in range(i,n):
c = sentence[j]
if c not in node.child:
dp[i] = min(dp[i], dp[j+1]+j-i+1)
break
if node.child[c].is_word:
dp[i] = min(dp[i],dp[j+1])
else:
dp[i] = min(dp[i], dp[j+1]+j-i+1)
node = node.child[c]
return dp[0]
三、回溯法
class Solution:
def respace(self, dictionary: List[str], sentence: str) -> int:
dictionary = set(dictionary)
llen = list({len(w) for w in dictionary})
llen.sort(reverse = True)
N, res, i = len(sentence), 0, 0
@functools.lru_cache(maxsize = 1000)
def huisu(i):
if i >= N:
return 0
tails = [huisu(i+l) for l in llen if i+l <= N and sentence[i:i+l] in dictionary]
tails += [1+huisu(i+1)]
return (min(tails) if tails else 0)
return huisu(0)