Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

恢复空格

来自Leetcode面试题17.13 恢复空格

哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"I reset the computer. It still didn’t boot!"已经变成了"iresetthecomputeritstilldidntboot"。在处理标点符号和大小写之前,你得先把它断成词语。当然了,你有一本厚厚的词典dictionary,不过,有些词没在词典里。假设文章用sentence表示,设计一个算法,把文章断开,要求未识别的字符最少,返回未识别的字符数。

注意:本题相对原题稍作改动,只需返回未识别的字符数

示例:

1
2
3
4
5
输入:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
输出: 7
解释: 断句后为"jess looked just like tim her brother",共7个未识别字符。

动态规划

dp[i] 表示字符串的前 i 个字符的最少未匹配数。

假设当前我们已经考虑完了前 i 个字符了,对于前 i + 1 个字符对应的最少未匹配数:

  1. i + 1 个字符未匹配,则 dp[i + 1] = dp[i] + 1,即不匹配数加 1;
  2. 遍历前 i 个字符,若以其中某一个下标 idx 为开头、以第 i + 1 个字符为结尾的字符串正好在词典里,则 dp[i] = min(dp[i], dp[idx]) 更新 dp[i]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int respace(String[] dictionary, String sentence) {
Set<String> dict = new HashSet<>(Arrays.asList(dictionary));
int len = sentence.length();
//dp[i]表示字符串前i个字符的最少未匹配数
int[] dp = new int[len+1];
for(int i = 1 ; i <= len ; ++i){
//多了一个未识别数
dp[i] = dp[i-1] + 1;
for(int index = 0 ; index < i ; index++){
//i从1开始,index从0开始,很巧妙
//相当于是倒着遍历
if(dict.contains(sentence.substring(index,i)))
dp[i] = Math.min(dp[i],dp[index]);
}
}
return dp[len];
}

Trie树

//todo