LeetCode:Word Break II

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

 
class Solution {
public:

    vector<string> myString;
    
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
     <span style="white-space:pre">	</span>vector<string> result;
	result.clear();
	if(s.empty()||dict.empty())
		return result;
	bool* dp = new bool[s.size() + 1];
	map<int,vector<int>> index;
	memset(dp,false,s.size() + 1);
	dp[0] = true;

	for(int i=1;i<s.size()+1;i++)
	{
	<span style="white-space:pre">	</span>for(int j=0;j<i;j++)
		{
			if(dp[j])
			{
				string str = s.substr(j,i-j);
				dp[i] = (dict.find(str) != dict.end())?true:false | dp[i];
				if(dict.find(str) != dict.end())
				{
					map<int,vector<int>>::iterator it = index.find(i);
					if(it!=index.end())
						it->second.push_back(j);
					else
					{
						vector<int> temp;
						temp.push_back(j);
						index.insert(make_pair(i,temp));
					}	
					continue;
				}
			}
		}
	}
	
	if(!dp[s.size()])
		return result;
	else
		report(s,index,result,s.size());

	return result;
    }
    
    void report(string &s,map<int,vector<int>>& index, vector<string>& result,int n)
   {
	if(n == 0)
	{
		string str;
		for(int i = myString.size()-1;i>=0;i--)
		{
			str+=myString[i];
			if(i!=0)
				str.push_back(' ');
		}
		result.push_back(str);

	}
	else
	{
		map<int,vector<int>>::iterator it = index.find(n);
		if(it!=index.end())
		{
			for(int i = 0; i<it->second.size();i++)
			{
				myString.push_back(s.substr(it->second[i],n - it->second[i]));
				report(s,index,result,it->second[i]);
				myString.pop_back();
			}
			
		}
	}
   }
};
继word break,首先用word break的方法判断是否可以匹配,然后利用保存的路径返回结果。

路径的保存用到了map,map的索引为字符串的字符对应的下标,索引对应的值为一个数组,该数组保存着以该索引为末尾字符的在dict中的匹配串的开始字符对应的下标。

例:

s = "abcd"

dict = ["a","b","abc","cd"]


map最终为

[

1->{0}

2->{1}

3->{0}

4->{2}

]


这样,当输出结果时,以尾字符开始递归查询,具体如下:

map.find(4)->second[0]=2   <----------------->  s.substr(2,4-2) = "cd"

map.find(2)->second[0]=1   <----------------->  s.substr(1,2-1) = "b"

map.find(1)->second[0]=0   <----------------->  s.substr(0,1-0) = "a"


将“a”、“b”、“cd”组合即可

已AC 52ms


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值