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".
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = s.length();
int matrix[n][n];
for(int i = 0;i<n;i++)
memset(matrix[i],0,n*sizeof(int));
for(int l = 1;l<=n;l++)
{
for(int i = 0;i<n-l+1;i++)
{
int j = i+l-1;
if(dict.find(s.substr(i,l)) != dict.end()) {
matrix[i][j] = 1;
continue;
}
for(int k = i;k<j;k++)
{
if(matrix[i][k] == 1 && matrix[k+1][j] == 1) matrix[i][j] = 1;
}
}
}
return (matrix[0][n-1] == 1)?true:false;
}
};
36 ms.
也可以写成
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = s.length();
int dp[n+1];
memset(dp,0,(n+1)*sizeof(int));
dp[0] = 1;
for(int i = 0;i<n;i++)
{
for(int j = i;j>=0;j--){
if(dp[j] && dict.find(s.substr(j,i-j+1)) != dict.end()){
dp[i+1] = 1;
break;
}
}
}
return (dp[n]==1)?true:false;
}
};
20 ms
2787

被折叠的 条评论
为什么被折叠?



