leetcode 139. Word Break

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值