`
frank-liu
  • 浏览: 1666001 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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://leetcode.com/problems/word-break-ii/

 

问题分析

  关于这个问题的递归推导关系实际上和前一个问题是一样的。对于长度i的字符串来说,它包含的字符串的划分等于所有wordBreak(s.substring(0, j)) + s.substring(j, i)(j >= 0 j < i)。这样,在这个问题里,我们需要在对应s的每个位置设置一个对应的List<String>,这样当后面碰到一个匹配的情况下,我们就将第j个位置的list里的每个元素,和s.substring(j, i)串起来加入到新的列表中。这个新的列表就构成了i位置的列表。

  于是我们就有了第一种方法。

 

动态规划法

  有了前面的讨论,我们需要在每个位置建立对应的List<String>,因此在实现的时候可以采用一个Map<Integer, List<String>> map。key表示s里面每个索引的值,value表示每个索引位置对应的list。剩下的就是我们采用类似的两层遍历,建立这个列表。

  有了之前的讨论,我们得到的代码如下:

 

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        Map<Integer, List<String>> map = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("");
        map.put(0, l);
        for(int i = 1; i <= s.length(); i++) {
            List<String> values = new LinkedList<>();
            for(int j = 0; j < i; j++) {
                if(wordDict.contains(s.substring(j, i))) {
                    for(String word: map.get(j)) {
                        values.add((word.isEmpty() ? "" : (word + " ")) + s.substring(j, i));
                    }
                }
            }
            map.put(i, values);
        }
        return map.get(s.length());
    }
}

  这部分代码的时间复杂度达到了O(n ^ 3) 。虽然结果是正确的,但是在字符串比较长的时候容易超时。

 

改进

  我们看前面的方法,它在元素长度比较长而且有很多重复的情况下,会出现有很多的匹配,而这里针对每个匹配,它要在不同的索引下面建立新的列表并且拷贝添加元素进去。这样会消耗大量的时间。而对于之前的情况它的根源在于有很多重复的子串,我们完全可以跳过这些子串去重用它们,而不是每次要构建一个索引位置的串。这些不同索引位置的串中间出现的大量重复才是关键点。

  于是,我们可以考虑不是针对索引位置建立列表,而是针对不同的串来建立列表。这样当有重复的子串是,我们根据串所对应的列表来加入对应的元素就可以了。这样节约了一个个拷贝的时间。

  从实现的细节来说,我们可以定义一个全局的Map<String, List<String>>  map。这里记录某个长度的串所对应的划分。我们从字符串索引1的位置开始,每次判断s.substring(0, i),如果dict包含有这个串,则递归的将当前子串和wordBreak(s.substring(i), dict)的结果加入到当前列表中。当然,我们在函数中会判断map中或者dict中是否已经包含有当前串s了,如果有,就直接返回。

  详细的代码实现如下:

 

public class Solution {
    Map<String, List<String>> mem = new HashMap<>();
    public List<String> wordBreak(String s, Set<String> dict) {
        if (mem.get(s) != null) return mem.get(s);
        List<String> result = new ArrayList<>();
        if (dict.contains(s)) result.add(s);
        for (int i = 1; i < s.length(); i++) {
            String word = s.substring(0, i);
            if (dict.contains(word)) {
                List<String> tmp = wordBreak(s.substring(i), dict);
                for (String str : tmp) {
                    result.add(word + " " + str);
                }
            }
        }
        mem.put(s, result);
        return result;
    }
}

 

分享到:
评论

相关推荐

    LintCode 582: Word Break II

    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. Example Example 1...

    LeetCode:LeetCode解决方案

    preorder-traversal链表reorder-list链表linked-list-cycle-ii链表linked-list-cycle动态规划word-break-ii动态规划word-break链表copy-list-with-random-pointer复杂度single-number-ii复杂度single-number动态规划

    leetcode530-leetcode:力扣在线评委

    leetcode 530 力扣在线评委 # 问题 困难 解决方案 1 简单的 2 中等的 3 中等的 12 中等的 22 中等的 39 中等的 94 中等的 108 中等的 122 中等的 136 中等的 144 中等的 167 中等的 238 中等的 260 中等的 268 中等...

    gasstationleetcode-leetcode:LeetcodeOJ解决方案

    leetcode 【演示记录】 报告 展示 2017/03/06 1.二和,167.二和二 2107/03/06 15.3 总和,16.3 总和最近,18.4 总和,11.最多水的容器 2017/03/09 62.Unique Paths, 63.Unique Paths II, 64.Minimum Path Sum 2017/...

    扩展矩阵leetcode-Leetcode:LeetcodeAnswer-Java

    扩展矩阵leetcode Leetcode Leetcode Answer-Java 数组 11.乘最多水容器 ...wordBreak 279.完全平方数 numSquares 排序 56.合并区间 merge 75.颜色分类 sortColors 179.最大数 largestNumber 324.摆

    leetcode苹果-word-break:断字

    leetcode 苹果断字 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以被分割成一个或多个字典单词的空格分隔序列。 笔记: 字典中的同一个词可能会在切分中重复使用多次。...word. E

    LeetCode最全代码

    318| [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | [C++](./C++/maximum-product-of-word-lengths.cpp) [Python](./Python/maximum-product-of-word-...

    wordbreakleetcode-WordBreak-Leetcode-139:一种使用动态规划来确定一个词是否可以作为给定词典中所有词的串

    断字leetcode WordBreak-Leetcode-139 Leetcode 问题 139(中) 问题中使用的技术:动态规划

    leetcode338-coding_notebook:编码_笔记本

    第 338 章概括 [(雅虎)4。...问题/数组和字符串/140.word_break_ii.md) [151. 反转字符串中的单词](Leetcode Problems/Array and String/151.reverse_words_in_a_string.md) [167. Two Sum 2 - In

    lrucacheleetcode-leetcode-in-go:leetcode-in-go

    lru缓存leetcode Go 中解决的一些 Leetcode 问题 大批 3sum-0015 买卖股票的最佳时机-0121 最多水的容器-0011 contains-duplicate-0217 find-minimum-in-rotated-sorted-array-0153 ...word-break-0139 图形

    wordbreakleetcode-WordBreak:“断字”问题的解决方案。用C#编写

    断字leetcode 断字 “断字”问题的解决方案。 用 C# 编写 Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. ...

    dynamic-programming:动态编程

    动态编程递归无重复每个子问题只能评估一次天真的递归方法由于重复而花费指数时间自上而下的回忆这是递归的深度优先搜索实现缓存重复工作自下而上基于依赖图将递归转换为依赖图它是有向无环图您可以使用拓扑排序对......

    cpp-算法精粹

    Word Break II Dungeon Game House Robber House Robber II House Robber III Range Sum Query - Immutable Range Sum Query 2D - Immutable 图 Clone Graph 位操作 Reverse Bits Repeated DNA Sequences Number of ...

Global site tag (gtag.js) - Google Analytics