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 n = s.size();
vector<bool> p(n + 1,false);
p[0] = true;
for(int i = 0;i < n;i ++){
if(p[i]){
for(int step = 1;i + step - 1 < n;step ++){
if(dict.count(s.substr(i,step)) > 0)
p[i + step] = true;
}
}
}
return p[n];
}
};