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 =
dict =
s =
"leetcode"
,dict =
["leet", "code"]
.
Return true because
"leetcode"
can be segmented as "leet code"
. bool wordBreak(string s, unordered_set<string> &dict) {
int l = s.length();
vector< vector<int> > m (l, vector<int>(l,0));
for (int i = 0; i <l; i++)
{
for (int j = i; j < l; j++)
{
if (dict.find(s.substr(i,j-i+1)) != dict.end())m[i][j] = 1;
}
}
for (int k = 2; k<=l ; k++)
{
for(int i = 0; i+k-1 < l ; i++)
{
int j = i+k-1;
for (int p = i; p <j; p++)
{
if(m[i][p] && m[p+1][j]){m[i][j] = true; break;}
}
}
}
return m[0][l-1];
}
No comments:
Post a Comment