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".class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if (s.size()<=0 || dict.size()<=0)
return false;
vector<bool> res = vector<bool>(s.size(),false);
if (dict.find(s.substr(0,1))!=dict.end())
res[0]=true;
for (int i=1;i<s.size();i++)
{
if (dict.find(s.substr(0,i+1))!=dict.end())
{
res[i]=true;
continue;
}
for (int k=0;k<i;k++)
{
if (res[k]== true && dict.find(s.substr(k+1,i-k))!=dict.end())
{
res[i]=true;
break;
}
}
}
return res[s.size()-1];
}
};
No comments:
Post a Comment