zoukankan      html  css  js  c++  java
  • 【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"].


    题解:开始想利用Word Break I的代码(详细请见http://www.cnblogs.com/sunshineatnoon/p/3849154.html),先把dp的表打出来,然后DFS搜索出字符串,后来发现这样会TLE。看了九章的题解,才有了如下思路:

    递归的思想,利用一个map——Map<String, ArrayList<String>> map存放单词s和它对应的拆分字符串的列表。比如题目中的例子catsanddog在map中的对应的list就有两个元素"cats and dog"和"cat sand dog"。

    因为每个字符串s如果有划分,那么一定从第一个字符开始,所以,递归每次从索引0开始,找到dict中包含的s的前缀,然后递归的探求s除去这个前缀后剩下的字符串可以被拆分成的方式,如果剩下的字符串可以被拆分,那么前缀加上剩下字符串拆分得到的结果就是最终s的拆分结果了。

    还是以题目中的例子来说"catsanddog"

    首先发现dict中含有前缀cat,这时递归的去找"sanddog"的拆分方式,发现可以拆分为”sand dog",最终得到s的一种拆分方式"cat sand dog";

    继续循环,发现dict中含有前缀"cats",这时递归的去找"anddog"的拆分方式,发现可以拆分为"and dog",最终得到s的第二种拆分方式"cats and dog"。

    代码如下:

     1 public class Solution {
     2     public List<String> wordBreak(String s, Set<String> dict) {
     3         Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
     4         return findList(s, dict, map);
     5     }
     6     private List<String> findList(String s,Set<String> dict,Map<String, ArrayList<String>> map){
     7         if(map.containsKey(s)) return map.get(s);
     8         ArrayList<String> answerList = new ArrayList<String>();
     9         int length = s.length();
    10         if(length <= 0)
    11             return answerList;
    12         
    13         for(int i = 1;i <= length;i++){
    14             String prefix = s.substring(0,i);
    15             if(dict.contains(prefix)){
    16                 if(i == length)
    17                     answerList.add(prefix);
    18                 else{                    
    19                     List<String> temp = findList(s.substring(i), dict, map);
    20                     for(String tmp:temp){
    21                         tmp = prefix + " " + tmp;
    22                         answerList.add(tmp);
    23                     }
    24                 }
    25             }
    26         }
    27         map.put(s, answerList);
    28         return answerList;
    29     }
    30 }
  • 相关阅读:
    jQuery Mobile方向感应事件
    Linq-多条件查询
    linux top命令详解
    在Python中调用C++,使用SWIG
    linux下core文件调试方法
    如何设置、查看以及调试core文件
    标准C++中的string类的用法总结(转)
    实用make最佳实践
    GDB多进程调试(转)
    GDB详解
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3849413.html
Copyright © 2011-2022 走看看