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"
.
DP:
first dp:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
vector<short> isOK(s.size() + 1, 0);
isOK[s.size()] = 1;
for (int i = s.size() - 1; i >= 0; i--) {
for (int j = i; j < s.size(); j++) {
if (dict.find(s.substr(i, j - i + 1)) != dict.end() && isOK[j + 1]) {
isOK[i] = 1;
break;
}
}
}
return isOK[0];
}
};
The thought is :
This dp is from the bottom. Suppose the string is "abcdefghijk", the word break is successful when "abcde" is in the dictionary and "fghijk" is successfully word break.
So, isOK[i] means the substr starting from i is successfully word break. In the inner loop, if we found a substr from i to j is in the dictionary and the rest substr from j + 1 to the end is OK, then isOK[i] = 1.
Notice that isOK[s.size()] = 1 because the substr is empty.
second dp:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
vector<short> isOK(s.size() + 1, 0);
isOK[0] = 1;
for (int i = 1; i <= s.size(); i++) {
for (int j = 1; j <= i; j++) {
if (dict.find(s.substr(j - 1, i - j + 1)) != dict.end() && isOK[j - 1]) {
isOK[i] = 1;
break;
}
}
}
return isOK[s.size()];
}
};
Notice that isOK[0] is just a start sign of 0 length, which is always true, so the i and j start from 1 but they both point to s[i - 1] or s[j - 1].