Word Break II

29 篇文章 0 订阅

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

 

牺牲内存换时间,有时是值得的,要吝惜空间,不要吝啬空间!

 

class Solution {
public:
	int maxlen;
	unordered_map<int,vector<string> >okword;
	unordered_map<int, bool>avail;
	
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
		vector<string> rst;
	
		if(s.size() == 0 || dict.size() == 0)return rst;
         okword.clear();
		 avail.clear();
		 maxlen = 0;
		 

		for(unordered_set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
		{
			if(maxlen < it->size())maxlen = it->size();
		}

		
		if(caculate_okwords(0, s, dict))
		{
			string str;
			generate_rst(0, s.size(), str,rst);
		}

		return rst;

		
    }
	//功能分开,更清楚高效,内聚越高越好,能分开的模块就分出来
	void generate_rst(int i, int size,string &sentence, vector<string> &rst)
	{
		if(i == size)
		{
			rst.push_back(sentence);
			return;
		}

		vector<string> strs = okword[i];
		for(int idx = 0; idx < strs.size(); ++idx)
		{
			string tmp = sentence;
			
			if(i) sentence += " ";
			sentence += strs[idx];
			generate_rst(i + strs[idx].size(), size, sentence, rst);
			sentence = tmp;
		}

		return ;
		
	}
	
	bool caculate_okwords(int i,string s, unordered_set<string> &dict)
	{
		
		if(i == s.size())return true;
		
		if(avail.find(i) != avail.end())return avail[i];
		
		int flag = 0;
		for(int len = 1; len <= maxlen && i + len <= s.size(); ++len)
		{
			string str = s.substr(i, len);
			if(dict.find(str) != dict.end())
			{
				bool rst = caculate_okwords(i + len, s, dict);
				if(rst)
				{
					flag = 1;
					okword[i].push_back(str);
					avail[i] = true;
				}
			}
		}
		if(flag)return true;
		
		avail[i] = false;//记得保存false的结果
		return false;
		
		
	}

	
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值