原 Leedcode11-word-break-ii

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"].

 

#include<iostream>
#include<vector>
#include<string>
using namespace std;
#include<unordered_set>

#if 0
class Solution {
public:
	vector<string> wordBreak(string s, unordered_set<string> &dict) {
		vector<string> v;
		string ss = "";
		for (unordered_set<string>::iterator it=dict.begin();it!=dict.end();it++)
		{
			int pos=s.find(*it);
			int poss = ss.find(*it);
			if (poss >= 0)
			{
				break;
			}	
			else if (pos >= 0)
			{
				ss += (*it)+" ";
				/*int n = pos + (*it).size();
				int m = s.size();*/
				
			}		
		}
		v.push_back(ss);
		return v;
	}
};

#endif
#if 1

class Solution {
public:
	vector<string> wordBreak(string s, unordered_set<string> &dict) {  //catsanddog
		vector<string> result;
		if (dict.find(s) != dict.end())
			result.push_back(s);
		for (int i = 1; i<s.size(); i++)
		{
			string w = s.substr(i);  //截取i之后的字符串
			if (dict.find(w) == dict.end())
				continue;
			string str = s.substr(0, i);
			vector<string> left = wordBreak(str, dict);
			Add(left, w);
			//void insert( iterator loc, input_iterator start, input_iterator end )
			//在指定位置loc前插入区间[start, end)的所有元素         
			result.insert(result.begin(), left.begin(), left.end()); 		
		}         
		return result;
	}
	void Add(vector<string> &str, string w)
	{
		for (vector<string>::iterator it = str.begin(); it != str.end(); it++)
			*it += " " + w;
	}
};

int main()
{
	string s = "catsanddog";
	unordered_set<string> dict;
	dict.insert("cat");
	dict.insert("cats");
	dict.insert("and");
	dict.insert("sand");
	dict.insert("dog");
	dict.insert("cat");
	vector<string> v =Solution().wordBreak(s, dict);
	for (vector<string>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << endl;
	}
	return 0;
}

#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值