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"].
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) {
bool flag=false;
if(1>s.length())
return true;
if(1==s.length())
return(dict.count(s));
for(int n=0;n<s.length()-1;n++)
{
if(dict.count(s.substr(0,n)))
if(dict.count(s.substr(n+1)))
return true;
else
flag=wordBreak(s.substr(n+1),dict);
}
}
};
注:超时