面试题 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中只包含小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/re-space-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 1 //使用字典树
 2 //字典树倒着存
 3 //计算时使用动态规划
 4 //若新增的元素i 与第start个字符可以组成单词 dp[i]=min(dp[i],dp[start-1]);
 5 //若未找到 dp[i]=dp[i-1]+1;
 6 class Trie
 7 {
 8     public:
 9     Trie* next[26]={0};
10     bool isEnd;
11     Trie():isEnd(false){};
12     void insert(string& s)
13     {
14         Trie* cur=this;
15         int len=s.length();
16         for(int i=len-1;i>=0;i--)
17         {
18             int t=s[i]-'a';
19             if(!cur->next[t])
20                 cur->next[t]=new Trie();
21             cur=cur->next[t];
22         }
23         cur->isEnd=true;
24     }
25 };
26 class Solution {
27 public:
28     int respace(vector<string>& dictionary, string sentence) {
29         Trie* dic=new Trie();
30         for(auto s:dictionary)
31             dic->insert(s);
32         int n=sentence.length();
33          vector<int> dp(n+1,0);
34          for(int i=1;i<=n;i++)
35          {
36              dp[i]=dp[i-1]+1;
37              Trie* cur=dic;
38              for(int j=i;j>0;j--)
39              {
40                 int t=sentence[j-1]-'a';
41                 if(!cur->next[t])
42                     break;
43                 else if(cur->next[t]->isEnd)
44                     dp[i]=min(dp[i],dp[j-1]);
45                 if(!dp[i])break;
46                 cur=cur->next[t];
47              }
48          }
49         return dp[n];
50     }
51 };

 

posted @ 2020-07-09 15:07  lancelee98  阅读(165)  评论(0编辑  收藏  举报