问题描述如下:
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"
.
cpp代码如下:
class Solution {
private:
vector<bool> flag;
bool wordbreak(const string& s,int pos,const unordered_set<string>& dict){
if(pos==(int)s.length()){
return true;
}
if(flag[pos]==false)return false;
string c="";
for(int i=pos;i<(int)s.length();++i){
c+=s[i];
if(dict.count(c)!=0&&wordbreak(s,i+1,dict))
return true;
}
flag[pos]=false;
return false;
}
public:
bool wordBreak(string s, unordered_set<string> &dict) {
flag.resize(s.length());
for(int i=0;i<(int)s.length();++i)
flag[i]=true;
return wordbreak(s,0,dict);
}
};