LeetCode每日一题:面试题17.13.恢复空格

题目描述

哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"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中只包含小写字母。

思路:

这是一道动态规划的问题,我的思路是使用一个标记数组 s t a t e _ v e c state\_vec state_vec 来记录序列 s e n t e n c e sentence sentence 中每个位置之前有多少字符无法识别。例如 s t a t e _ v e c [ 5 ] = 4 state\_vec[5]=4 state_vec[5]=4 就表示 s e n t e n c e [ 0 : 5 ] sentence[0:5] sentence[0:5] 中有4个字符无法被识别。

有了这个数组,在遍历序列的过程就使用暴力的方法,定义两个标记 i i i j j j,其中 i ∈ [ 0 , l e n ( s e n t e n c e ) ) , j ∈ [ 1 , m a x _ w o r d _ l e n g t h + 1 ) i\in[0,len(sentence)), j\in[1,max\_word\_length+1) i[0,len(sentence)),j[1,max_word_length+1)。这里的 m a x _ w o r d _ l e n g t h max\_word\_length max_word_length 是指词典中最长的单词的长度。遍历过程中, i i i 一步一步地向后移动,而对于每个 i i i j j j 也逐步向后探测。

当存在一个子序列 s e n t e n c e [ i : j ] sentence[i:j] sentence[i:j] 能够与词典当中的词匹配时, s t a t e _ v e c [ i + j ] state\_vec[i+j] state_vec[i+j] 的值为 m i n ( s t a t e _ v e c [ i + j ] , s t a t e _ v e c [ i ] ) min(state\_vec[i+j], state\_vec[i]) min(state_vec[i+j],state_vec[i]),也就是如果前面几个字母能匹配上字典当中的一个词,那么这个词后面位置的标记数组的值会取原数值和 i i i 位置的值的较小值。

如果在 j j j 的遍历过程中 s e n t e n c e [ i : j ] sentence[i:j] sentence[i:j] 无法匹配词典当中的词,那么 s t a t e _ v e c [ i + j ] state\_vec[i+j] state_vec[i+j] 的值要么保持不变,要么是前一个位置的值加1(取较小的值),即 s t a t e _ v e c [ i + j ] = m i n ( s t a t e _ v e c [ i + j ] , s t a t e _ v e c [ i + j − 1 ] + 1 ) state\_vec[i+j] = min(state\_vec[i+j], state\_vec[i+j-1] + 1) state_vec[i+j]=min(state_vec[i+j],state_vec[i+j1]+1)

遍历到最后,标记数组最后一个元素就是整个序列无法识别的字符数量。

代码(python):

dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
dictionary_set = set(dictionary)
max_word_length = 0
not_recog = 0
state_vec = [i for i in range(len(sentence)+1)]
for word in dictionary:
    max_word_length = max(len(word), max_word_length)
for i in range(len(sentence)):
    for j in range(1, max_word_length+1):
        if i+j > len(sentence):
            break
        if sentence[i:i+j] in dictionary_set:
            state_vec[i+j] = min(state_vec[i+j], state_vec[i])
        else:
            state_vec[i+j] = min(state_vec[i+j], state_vec[i+j-1] + 1)
not_recog = state_vec[len(sentence)]
print(not_recog)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值