• [leetcode] 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"].

    https://oj.leetcode.com/problems/word-break-ii/ 

    思路:DFS枚举。

    dfs超时

    public class Solution {
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        ArrayList<String> res = new ArrayList<String>();
        if(s==null || s.length()==0)
            return res;
        helper(s,dict,0,"",res);
        return res;
    }
    private void helper(String s, Set<String> dict, int start, String item, ArrayList<String> res)
    {
        if(start>=s.length())
        {
            res.add(item);
            return;
        }
        StringBuilder str = new StringBuilder();
        for(int i=start;i<s.length();i++)
        {
            str.append(s.charAt(i));
            if(dict.contains(str.toString()))
            {
                String newItem = item.length()>0?(item+" "+str.toString()):str.toString();
                helper(s,dict,i+1,newItem,res);
            }
        }
    }
    }

    第二遍记录: dfs写法,依然超时。

    public class Solution {
        public ArrayList<String> wordBreak(String s, Set<String> dict) {
            ArrayList<String> res = new ArrayList<String>();
            StringBuilder sb = new StringBuilder();
    
            wordBreakHelper(res, s, dict, sb);
    
            return res;
        }
    
        private void wordBreakHelper(ArrayList<String> res, String s, Set<String> dict, StringBuilder sb) {
            if ("".equals(s)) {
                res.add(sb.toString().substring(0, sb.length() - 1));
                return;
            }
    
            for (int i = 1; i <= s.length(); i++) {
                String left = s.substring(0, i);
                if (dict.contains(left)) {
                    sb.append(left + " ");
                    wordBreakHelper(res, s.substring(i), dict, sb);
                    sb.delete(sb.length() - left.length() - 1, sb.length());
                }
            }
    
        }
    
        public static void main(String[] args) {
    
            String s = "catsanddog";
            String[] a = { "cat", "cats", "and", "sand", "dog" };
            Set<String> dict = new HashSet<String>();
            for (String each : a)
                dict.add(each);
    
            System.out.println(new Solution().wordBreak(s, dict));
        }
    }
  • 相关阅读:
    【转】Delphi 关键字详解
    import datetime
    addlayer添加神经网络层
    xadmin使用富文本
    django安装xadmin
    django安装DjangoUeditor富文本
    django中admin一些方法
    Centos7.6安装python3.6.8
    django错误处理
    mysql 快速生成百万条测试数据
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3829438.html
Copyright © 2020-2023  润新知