【题目】
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
【解法】
看到这道题,第一反应就是深搜,暴力解法,代码如下:
bool wordBreak(string s, unordered_set<string> &dict) {
auto it = dict.find(s);
if(it != dict.end()){
return true;
}
for(int i = 0; i < s.length(); i++){
string str1 = s.substr(0,i);
string str2 = s.substr(i+1,s.length());
if(wordBreak(str1,dict) && wordBreak(str2,dict))
return true;
}
return false;
}
提交之后直接超时,然后分析发现其实是可以用dp去解决的,dp最主要的思想是找到重复子问题,推出状态方程,我们看这道题的状态方程,其实跟其他dp算法还是有点区别的,状态方程为f(i) = 存在j 使得f(j) && s[j+1,i]属于dict ,那么可以写出代码:
bool wordBreak(string s,unordered_set<string> &dict){
vector<bool> f(s.length()+1,false);
f[0] = true;
for(int i = 1; i < s.length()+1 ;i ++){
for (int j = i-1; j >= 0; j--){
if(f[j] && (dict.find(s.substr(j,i-j))!=dict.end())){//注意substr的用法,substr(pos,len)
f[i] = true;
}
}
}
return f[f.size()-1];
}