leetcode之Word Break

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 {
public:
    bool wordBreak(string s, unordered_set<string> &dict)
    {
    	int length = s.size();
    	vector<bool> dp(length + 1,false);
    	dp[length] = true;
    	int i,j;
    	for(i = length - 1; i >= 0; --i)
    	{
    		for( j = i; j < length; ++j)
    		{
    
    			string sub = s.substr(i,j - i + 1);
    			unordered_set<string>::iterator iter = dict.find(sub);
    			if(iter != dict.end() && dp[j+1])
    			{
    				dp[i] = true;
    			}
    		}
    	}
    	return dp[0];
    }
};

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:
void dfs(string s,unordered_set<string> &dict,string sub,vector<vector<bool> > seg,int start,int depth,int length,vector<string>& res)
{
	if(depth == length)
	{
		string t = sub.substr(0,sub.length()-1);//去除最后一个空格
		res.push_back(t);
		return;
	}
	for(int len = 1;len <= length;len++)
	{
		if(seg[start][len])//判断是否可以完全分割
		{
			string t = s.substr(start,len);
			unordered_set<string>::iterator iter = dict.find(t);
			if(iter != dict.end())
			{
				int beforeLen = sub.length();
				sub += t += " ";
				dfs(s,dict,sub,seg,start+len,start+len,length,res);
				sub = sub.substr(0,beforeLen);
			}
		}
	}
}
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> res;
	int length = s.size();
	if(length == 0 || dict.size() == 0)return res;

	int len,i,j;
	int MIN_LEN = numeric_limits<int>::max();
	unordered_set<string>::iterator iter = dict.begin();
	for(;iter != dict.end();iter++)
	{
		if((*iter).size() < MIN_LEN)MIN_LEN = (*iter).size();//找到字典中的最短单词的长度
	}

	vector<vector<bool> > seg;//用来判断当前子串是否可以完全分割,减少递归次数
	for(i=0;i<length;i++)
	{
		vector<bool> t;
		for(j=0;j<length+1;j++)
		{
			t.push_back(false);
		}
		seg.push_back(t);
	}

	for(len = MIN_LEN;len <= length;len ++)
	{
		for(i=0;i + len <= length;i++)
		{
			string sub = s.substr(i,len);
			iter = dict.find(sub);
			if(iter != dict.end())
			{
				seg[i][len] = true;
				continue;
			}
			for(j=1;j<len;j++)
			{
				if(seg[i][j] && seg[i+j][len-j])
				{
					seg[i][len] = true;
					break;
				}
			}
		}
	}
	if(seg[0][length] == false)return res;
	string sub = "";
	dfs(s,dict,sub,seg,0,0,length,res);
	return res;
    }
};


你可能感兴趣的:(LeetCode,break,面试,动态规划,word)