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"
.
Code:
<span style="font-size:14px;">class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
const int length = s.size();
bool *dp = new bool[length];
memset(dp, false, sizeof(bool)*length);
for (int i = 0; i < length; ++i)
if (dict.find(s.substr(0, i+1)) != dict.end())
dp[i] = true;
else {
for (int j = 0; j < i; ++j) {
if (dp[j] && dict.find(s.substr(j+1, i-j)) != dict.end()) {
dp[i] = true;
break;
}
}
}
bool result = dp[length-1];
delete [] dp;
return result;
}
};</span>