您的位置:首页 > 其它

**LeetCode—Word Break

2015-02-10 17:24 253 查看
Given a string s and a dictionary of words dict, determine ifs 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"
.

在这个例子当中,主要是为了看一个句子字符串中的词语能不能够都划分为词典中的词语

flag[j]为true,那么就是要求存在一个变量k,能够满足flag[k]为ture,同时substr(k,j-k)是在字典当中的

但是在这个例子当中是不关心最终的划分方式

class Solution {  
    public:  
        bool wordBreak(string s, unordered_set<string> &dict) {  
            int length = s.size();
	vector<bool> val(length+1,false);
	val[0] = true; //<根据长度进行设置
	int i = 0;
	int j = 0;
	for(i = 0; i < length; i++)
	{
		if(val[i])//<前一个长度是可以进行分解的
		{
			for(j = 1; (i+j) <= length; j++)
			{
				string tmp = s.substr(i,j);
				if(dict.count(tmp) > 0)
				{
					val[i+j] = true;
				}
			}
		}
	}
	return val[length];
        }  
    };


对应着有第二个例子:

Word Break II

Given a string s and a dictionary of words dict, add spaces ins 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"]
.

在这个例子当中,主要是需要将分解的结果放在一个vector的结构体当中
有一种方法是DFS 方法,还没有研究

这里主要还是借鉴了第一个例子当中的方法,先检测是否能够被划分,如果可以被划分,之后再通过遍历进行存储

class Solution {
public:
    void breakWord(vector<string> &res, string &s, unordered_set<string> &dict, string str, int idx, vector<bool> &dp) {
        string substr;
        for (int len = 1; idx + len <= s.length(); ++len) {
            if (dp[idx + len] && dict.count(s.substr(idx,len)) > 0) {
                substr = s.substr(idx, len);
                if (idx + len < s.length()) {
                    breakWord(res, s, dict, str + substr + " ", idx + len, dp);
                } else {
                    res.push_back(str + substr);
                    return;
                }
            }
        }
    }
    
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<bool> dp(s.length() + 1, false);
        dp[0] = true;
        for (int i = 0; i < s.length(); ++i) {
            if (dp[i]) {
                for (int len = 1; i + len <= s.length(); ++len) {
                    if (dict.count(s.substr(i, len)) > 0) {
                        dp[i + len] = true;
                    }
                }
            }
        }
        vector<string> res;
        if (dp[s.length()]) 
            breakWord(res, s, dict, "", 0, dp);
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: