[leetcode] 140. Word Break II

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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:

[]

分析

题目的意思是:给定一个字符串和一个单词字典,把该字符串分成一句子,句子中的每个单词都出现在字典中。

  • 这道题既可以用动态规划的方法,也可以用深度优先的方法。终止条件是遍历到字符串s的末尾。
  • 循环体为每次截取一个字串来在字典中查找是否存在,存在则继续递归,不存在则继续循环。

代码

class Solution {
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> dict(wordDict.begin(),wordDict.end());
        vector<bool> possible(s.size()+1,true);
        vector<string> ans;
        string item;
        dfs(s,0,dict,possible,ans,item);
        return ans;
    }
    
    bool dfs(string s,int index,unordered_set<string> dict, vector<bool> &possible, vector<string> &ans, string item){
        bool res=false;
        if(index==s.size()){
            ans.push_back(item.substr(0,item.size()-1));  // remove space in the end
            return true;
        }
        
        for(int i=index;i<s.size();i++){
            string word=s.substr(index,i-index+1);
            if(dict.find(word)!=dict.end()&&possible[i+1]){
                item=item+word+" ";
                if(dfs(s,i+1,dict,possible,ans,item)){
                    res=true;
                }else{
                    possible[i+1]=false;
                }
                item.resize(item.size()-word.size()-1);
            }
        }
        return res;
    }
};

参考文献

[编程题]word-break-ii
140. Word Break II

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值