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