1、动态规划。dp[i]表示以当前位置结束,能识别的最大字符数。dp[sentence]有了,相减就得了
2、dp[i]怎么求?以i结尾作为字符串截取匹配字典中每一个单词,然后取最大的那个。比如此时i来到的了string,字典中有["ng","ing"],遍历字典,dp[i] = Math.max(dp[i],dp[i - word.length()] + word.length())。for(String str : 字典集合)。如果无法匹配出str就进入下一个字段元素匹配,continue。第一个遍历"ng",string 可以匹配成"stri" "ng",所以此时dp[i] = dp[4] + 2。第二个遍历"ing",dp[i] = dp[3] + 3。dp[i]取最大的那个就可以了。
class Solution {
public int respace(String[] dictionary, String sentence) {
//从1开始,dp[i]代表的是以i结尾最长已经识别的字符数。
int[] dp = new int[sentence.length() + 1];
int right = 1;
while(right <= sentence.length()){
dp[right] = dp[right - 1];
//遍历字典中每个单词,如果以当前结束找到了单词word,那么次数dp[i]就该为dp[i - word.length()] + word.length();遍历过程中取最大即可。
for(String word : dictionary){
//如果当前长度不够就跳过等待变长。
if(right < word.length()){
continue;
}
//获取如果此时等于word的时候dp[i]的值为多少,会把字典遍历完,取最大的那个dp就行了。
String tmp = sentence.substring(right - word.length(),right);
//如果当前word不能组成,跳入下一个字典项
if(!tmp.equals(word)){
continue;
}
//找到了word,此时就是 比如:["123"] 234123,dp[6] = dp[6-3] + 3
dp[right] = Math.max(dp[right],dp[right - word.length()] + word.length());
}
right++;
}
return sentence.length() - dp[sentence.length()];
}
}