题解
单序列(DP_Sequence) DP 题,由单序列动态规划的四要素可⼤致写出:
1. State: f[i] 表⽰前 i 个字符能否根据词典中的词被成功分词。
2. Function: f[i] = or{f[j], j < i, letter in [j+1, i] can be found in dict} , 含义为⼩于 i 的索引 j 中只要有⼀个 f[j] 为真且 j+1 到 i 中组成的字符能在词典中找到时, f[i] 即为真,否则为假。具体实现可分为⾃顶向下或者⾃底向上。
3. Initialization: f[0] = true , 数组⻓度为字符串⻓度 + 1,便于处理。
4. Answer: f[s.length]
考虑到单词⻓度通常不会太⻓,故在 s 较⻓时使⽤⾃底向上效率更⾼。
这里面重点的就是在于判断:res[j] && dict.find(s.substr(j, i-j) != dict.find();
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.empty())
return true;
if(dict.empty()) return false;
int n = s.size();
vector<bool> res(n+1, false);
res[0] = true;
for(int i = 1; i <= n; ++i){
for(int j = i-1; j >= 0; j--){
if(res[j] && dict.find(s.substr(j, i-j)) != dict.end()){
res[i] = true;
break;
}
}
}
return res[n];
}
};