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

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

My Solution

大力出奇迹。
显然,从后往前找。对于位置 p ,若匹配上 dictionary[i] , 则有 ans[p] = min(ans[p], ans[p + dictionary[i].length()]); .
否则, ans[p] = ans[p + 1] + 1;.
答案即是 ans[0].

class Solution {
 public:
  int respace(vector<string>& dictionary, string sentence) {
    sort(dictionary.begin(), dictionary.end());
    if(dictionary.size() == 0)
      return sentence.length();

    vector<int>ans(sentence.length() + 1, 0);
    for(int p = sentence.length() - 1; p >= 0; p--) {
      string sub = sentence.substr(p, sentence.length() - p);
      ans[p] = ans[p + 1] + 1;
      for(int i = upper_bound(dictionary.begin(), dictionary.end(), sub) - dictionary.begin() - 1; i >= 0; i--) {
        if(dictionary[i][0] < sub[0] || ans[p] == 0)
          break;
        if(sub.length() < dictionary[i].length())
          continue;
        if(strncmp(sub.c_str(), dictionary[i].c_str(), dictionary[i].length()) == 0) {
          ans[p] = min(ans[p], ans[p + dictionary[i].length()]);
        }
      }
    }
    return ans[0];
  }
};
posted @ 2020-07-09 09:35  菁芜  阅读(155)  评论(0编辑  收藏  举报