zoukankan      html  css  js  c++  java
  • 140. 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 List<String> wordBreak(String s, List<String> wordDict) {
            List<String> res = new ArrayList();
            int l = s.length();
            boolean[] dp = new boolean[l + 1];
            dp[0] = true;
            for(int i = 1; i <= l; i++){
                for(int j = 0; j < i; j++){
                    if(dp[j] && wordDict.contains(s.substring(j, i))){
                        dp[i] = true;
                    }
                }
            }
            if(dp[s.length()] == false)   return res;
            help(s, wordDict, res, 0, "");
            return res;
        }
        public void help(String s, List<String> wordDict, List<String> res, int start, String tmp){
            if(start == s.length()){
                res.add(tmp);
                return;
            }
            if(tmp.length() != 0) tmp += " ";
            for(int i = start; i < s.length(); i++){
                String word = s.substring(start, i+1);
                if(!wordDict.contains(word)) continue;
                help(s, wordDict, res, i + 1, tmp + word);
            }
        }
    }

    需要先判断是否能进行word break再通过dfs求path。

    
    
  • 相关阅读:
    Android中的httpclient框架发送get请求
    成员函数的重载&amp;&amp;隐藏&amp;&amp;覆盖
    子墨庖丁Android的ActionBar源代码分析 (一)实例化
    Hadoop2.x介绍与源代码编译
    NFS 服务器的配置
    tftp 服务器的配置
    LINUX内核及应用程序移植工作
    u-boot 移植工作目录
    Linux 下工作用户及环境
    zless
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11756559.html
Copyright © 2011-2022 走看看