zoukankan      html  css  js  c++  java
  • [LeetCode] 140. Word Break II java

    题目:

    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. You may assume the dictionary does not contain duplicate words.

    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"].

    题意及分析:给出一个字符串和一个字典,求能用字典里的单词将字符串分割的所有可能。使用深度遍历的方法,每次判断字符串是否以字典中的单词为开头,如果是开头,继续判断剩余的字符串;如果最后字符串长度为0,那么就找到了能分割字符串的单词组成。这里用一个hashMap保存中间结果,否则会超时。

    代码:

    class Solution { 
        public List<String> wordBreak(String s, List<String> wordDict) {
            return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
        }
    
        List<String> DFS(String s,List<String> wordDict,HashMap<String,LinkedList<String>> map){
            if(map.containsKey(s))
                return map.get(s);
            LinkedList<String> res = new LinkedList<>();
            if(s.length() == 0){
                res.add("");
                return res;
            }
            for(String word : wordDict){
                if(s.startsWith(word)){
                    List<String> subList = DFS(s.substring(word.length()),wordDict,map);
                    for(String sub : subList){
                        res.add(word + (sub.isEmpty() ? "":" ")+ sub);
                    }
                }
            }
            map.put(s,res);
            return res;
        }
    }
  • 相关阅读:
    栈及其在.NET FrameWork中的源码分析
    《高性能网站建设指南》读书笔记
    九宫格数独问题
    队列及其在.NET FrameWork中的源码分析
    《web标准之道》读后感(书评)
    SharePoint中的权限体系
    关于异步方法调用
    WF4.0 Beta2:关于动态保存和装载XAML工作流
    Lotus Symphony介绍及试用
    Node.js 0.8.18 / 0.9.7 发布
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7680586.html
Copyright © 2011-2022 走看看