您的位置:首页 > 其它

leetcode 139. Word Break

2016-03-08 13:37 387 查看
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 {
bool do_once(set<string>&strs, map<char,vector<string>>& mywordDict)
{
set<string>newstrs;
for(set<string>::iterator it=strs.begin();it!=strs.end();it++)
{
string ss=*it;
if(mywordDict.find(ss[0])!=mywordDict.end())
for(int j=0;j<mywordDict[ss[0]].size();j++)
{
if(ss.length()>=mywordDict[ss[0]][j].length())
{
if(string(ss.begin(),ss.begin()+mywordDict[ss[0]][j].length())
.compare(mywordDict[ss[0]][j])==0)
{
if(ss.length()==mywordDict[ss[0]][j].length())
return true;
else
newstrs.insert(string(ss.begin()+mywordDict[ss[0]][j].length(),ss.begin()+ss.length()));
}
}
}
}
strs=newstrs;
return false;
}

public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(s.empty())
return true;
if(wordDict.empty())
return false;
set<char>aa,bb;
for(int i=0;i<s.length();i++)
aa.insert(s[i]);
for(unordered_set<string>::iterator it=wordDict.begin();it!=wordDict.end();it++)
for(int j=0;j<it->length();j++)
bb.insert((*it)[j]);
if(aa.size()>bb.size())
return false;
for(set<char>::iterator it=aa.begin();it!=aa.end();it++)
if(bb.find(*it)==bb.end())
return false;
map<char,vector<string>>mywordDict;
for(unordered_set<string>::iterator it=wordDict.begin();it!=wordDict.end();it++)
mywordDict[(*it)[0]].push_back(*it);
set<string>strs;
strs.insert(s);
bool f=do_once(strs,mywordDict);
while(!f&&!strs.empty())
{
f=do_once(strs,mywordDict);
}
return f;
}
};

accepted
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: