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"
.
动态规划。m[i][j]表示子串s[i,j]能否被组合。则递推式s[i][j] = (wordDict.find(s[i,j])?true: (存在t使得s[i][t] && s[t+1][j]吗?true:false)
时间复杂度O(n^3),空间复杂度O(n^2)
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.length();
bool **m = new bool*[n];
for(int i=0;i<n;i++){ m[i] = new bool[n]; memset(m[i],0,n);}
for(int k=1;k<=n;k++){
for(int i=0;i<=n-k;i++){
int j=i+k-1;
if(wordDict.find(s.substr(i,k))!=wordDict.end()) m[i][j] = true;
else{
for(int t=i;t<j;t++) if(m[i][t] && m[t+1][j]){ m[i][j] = true; break;}
}
}
}
return m[0][n-1];
}
};
那有没有更快的算法呢?有!
我们其实没有必要检查每个s[i,j]是否能被组合,这样会多做很多无用功。事实我们只需检查每个s[0,i]能否被组合就可以了。那有人可能会问,求m[0][i]不需要用到m[t][i]吗?
现在假设m[0][t-1]和m[t][i]都为true,那我只需找到s[t,i]子串的最后一个可被组合的单词,这个单词必然在wordDict中,不妨设这个单词的起始下标为t2,那就一定会有
m[0][t2-1]==true,所以m[0][i] = m[0][t2-1] && wordDict.find(s.substr(t2,i-t2+1)),根本无需知道m[t][i]
改进的时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.length();
bool *m = new bool[n+1];
memset(m,0,n+1);
m++;
m[-1] = true;
for(int i=0;i<n;i++){
for(int j=i-1;j>=-1;j--)
if(m[j] && wordDict.find(s.substr(j+1,i-j))!=wordDict.end()){
m[i] = true; break;
}
}
return m[n-1];
}
};