leetcode word break

1.Word Break 拆分词句

 

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

这里我们就用一个一维的dp数组,其中dp[i]表示范围[0, i)内的子串是否可以拆分,注意这里dp数组的长度比s串的长度大1,是因为我们要handle空串的情况,我们初始化dp[0]为true,然后开始遍历。注意这里我们需要两个for循环来遍历,因为此时已经没有递归函数了,所以我们必须要遍历所有的子串,我们用j把[0, i)范围内的子串分为了两部分,[0, j) 和 [j, i),其中范围 [0, j) 就是dp[j],范围 [j, i) 就是s.substr(j, i-j),其中dp[j]是之前的状态,我们已经算出来了,可以直接取,只需要在字典中查找s.substr(j, i-j)是否存在了,如果二者均为true,将dp[i]赋为true,并且break掉,此时就不需要再用j去分[0, i)范围了,因为[0, i)范围已经可以拆分了。最终我们返回dp数组的最后一个值,就是整个数组是否可以拆分的布尔值了,代码如下

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        vector<bool> dp(s.size() + 1);
        dp[0] = true;
        for (int i = 0; i < dp.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (dp[j] && wordSet.count(s.substr(j, i - j))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp.back();
    }
};

2.Word Break II 拆分词句之二

 

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
class Solution {

public:
       vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> result;
        if(dict.find(s)!=dict.end())
            result.push_back(s);
        for(int i=0;i<s.size();i++) 
        {
            string w = s.substr(i);
            if(dict.find(w) == dict.end())
                continue;
            string str = s.substr(0,i);
            vector<string> left = wordBreak(str,dict);
            Add(left,w);
            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;    
    }

};
链接:https://www.nowcoder.com/questionTerminal/bd73f6b52fdc421d91b14f9c909f9104
来源:牛客网

class Solution {
private:
    map<string, vector<string>> mp;
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> res;
        if(mp.count(s)) return mp[s];
        if(dict.count(s))
            res.push_back(s);
        for(int i=1; i<s.size(); i++)
        {
            string word = s.substr(i);
            if(dict.count(word))
            {
                string preStr = s.substr(0,i);
                vector<string> preVec = wordBreak(preStr, dict);
                combine(preVec, word);
                res.insert(res.begin(), preVec.begin(), preVec.end());
            }
        }
        mp[s] = res;
        return res;
    }
 
    void combine(vector<string> &vec, string word)
    {
        for(int i=0; i<vec.size(); i++)
        {
            vec[i] = vec[i] + " " + word;
        }
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值