- 结果
- 分析
使用DP的方法解决的,dp[i]表示sentence[i]之前可以用dictionary[]中字符串匹配的最大的长度。如果我们先忽略dictionary是一个数组(先把问题简单化,先解决sentence中只有一个字符串temp的情况),那么状态转移方程很好想。len = temp.length();
如果sentence[i - len + 1,i]和temp相同,那么dp[i] = dp[i - 1] > dp[i - len ] + len ? dp[i - 1] : dp[i - len ] + len。再把问题复杂化,把dictionary看成一个数组,这个时候只需要遍历一遍数组,找到这个位置可能的最大值即可。代码如下:
- 代码
bool cmp(const string & a, const string& b){//注意,这个函数必须写在类外
return a.length() < b.length();
}
class Solution {
public:
int respace(vector<string>& dictionary, string sentence) {
int size = dictionary.size();
int len = sentence.length();
if(len == 0) return 0;
int dp[len];
memset(dp, 0 , 4 * len);
sort(dictionary.begin(), dictionary.end(), cmp);
for(int i = dictionary[0].length() - 1; i < len; i++){
int max = i > 0 ? dp[i - 1] : 0;
for(int j = 0; j < size; j++){
int len = dictionary[j].length();
int index = i - (len - 1);
if(index >= 0){
if(strncmp(&sentence[index], &dictionary[j][0], len) == 0){
int temp = 0;
//注意下面的细节问题
if(index - 1 >= 0 && dp[index - 1] + len > dp[i - 1]) temp = dp[index - 1] + len;
else{
temp = index - 1 >= 0 ? dp[i - 1] : len;
}
max = max < temp ? temp : max;
}
}
}
dp[i] = max;
}
return len - dp[len - 1] ;
}
};