Description:
Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.
Example
Given s =
"lintcode"
, dict =["lint", "code"]
.Return true because
"lintcode"
can be break as"lint code"
.
Solution:
class Solution {
public:
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
bool wordBreak(string s, unordered_set<string> &dict) {
// write your code here
auto len = (int)s.length();
if (len == 0) return true;
vector<bool> vec(len+1, false);
vec[0] = true;
int maxLen = 0;
for (auto& e : dict) maxLen = max(maxLen, (int)e.length());
for (int i = 1; i <= len; ++i) {
for (int j = i-1; j >= 0 && i-j <= maxLen; --j) {
if (!vec[j]) continue;
if (dict.find(s.substr(j, i-j)) != dict.end()) {
vec[i] = true;
break;
}
}
}
return vec[len];
}
};