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"
.
bool wordBreak(string s, unordered_set<string> &dict)
{
if(s.length() < 1)
return true;
if(dict.empty())
return false;
//首先获得dict中最长单词的长度和最短单词的长度
unordered_set<string>::iterator itr = dict.begin();
int maxLength = (int)(*itr).length();
int minLength = (int)(*itr).length();
while(++itr != dict.end())
{
if((*itr).length() > maxLength)
{
maxLength = (int)(*itr).length();
}
if((*itr).length() < minLength)
{
minLength = (int)(*itr).length();
}
}
set<string> unMatch;
return wordBreakCore(s, dict, unMatch, maxLength, minLength);
return true;
}
bool wordBreakCore(string s, unordered_set<string> &dict, set<string> &unMatch, int &maxLength, int &minLength)
{
if(s.size() < 1)
return true;
unsigned long mx = maxLength > s.length() ? s.size() : maxLength;
for(int i = (int)mx; i >= minLength; i--)
{
string tmpWord = s.substr(0, i);
unordered_set<string>::iterator itr = dict.find(tmpWord);
if(itr != dict.end())
{
string leftStr = s.substr(i);
set<string>::iterator leftItr = unMatch.find(leftStr);
if(leftItr != unMatch.end())
{
continue;
}
else
{
if(wordBreakCore(leftStr, dict, unMatch, maxLength, minLength))
{
return true;
}
else
{
unMatch.insert(leftStr);
}
}
}
}
return false;
}