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"
.
Solution:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int len = s.length();
if(!len) return true;
vector<bool> dp(len + 1, false);
dp[0] = true;
int minN = 0x3fffffff, maxN = 0xffffffff;
for(auto d : wordDict)
{
minN = min(minN, (int)d.length());
maxN = max(maxN, (int)d.length());
}
for(int i = 0; i < len; ++i)
{
if(dp[i])
{
for(int j = minN; i + j <= len && j <= maxN; ++j)
{
if(wordDict.count(s.substr(i, j))) dp[i+j] = true;
}
}
}
return dp[len];
}
};