您的位置:首页 > 其它

leetcode之Word Break

2014-12-06 10:49 399 查看
问题描述如下:

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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: