难度中等75收藏分享切换为英文关注反馈
哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"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
中只包含小写字母。
动态规划,设dp[i]表示前i个字符中最少的未识别单词数量,每次转移时我们考虑第j到i个字符组成的子串sentence[j...i]能否在字典中找到,如果找到,dp[i]=min(dp[i],dp[j-1]),若找不到,dp[i]=dp[i-1]+1即可。python语言写匹配字典十分便捷,使用c/c++语言需要使用到字典树或字符串哈希(都忘了。。。)
class Solution:
def respace(self, dictionary: List[str], sentence: str) -> int:
l = len(sentence)
dp = [1100 for _ in range(l+1)]
dp[0] = 0
for i in range(1, l+1):
dp[i] = dp[i-1]+1
for j in range(i,0,-1):
if sentence[j-1:i] in dictionary:
dp[i] = min(dp[i], dp[j-1])
if dp[i]==0:
break
return dp[l]