地址
https://leetcode-cn.com/problems/word-break/
描述
思想
可以借助字符串哈希的方式,减少时间复杂度,这个之后有时间再研究吧。
代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n=s.length();
vector<bool> f(n+1,false);
//将wordDict中出现的字符串加入set中
//这种unordered_set的初始化学一下
unordered_set<string> hash(wordDict.begin(),wordDict.end());
f[0]=true;
for(int i=1;i<=n;i++){
for(int j=0;j<i;j++){
//f[j]==true且[j,i]字符串在hash中出现过
//这部分还可以改进
if(f[j] && hash.find(s.substr(j,i-j))!=hash.end()){
f[i]=true;
break;
}
}
}
return f[n];
}
};