Problem link:

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

This problem is some extension of the word break problem, so the solution is based on the discussion in Word Break.

We also use DP to solve the problem. In this solution, A[i] is not a boolean any more, but a list of all possible value of j>i such that s[i..j-1] is a word and A[j]==True. The pseudo-code for computing the array is similar to that in Word Break with a few modifications

WORD-BREAK(string s, dictionary d):
let A[0..n-1] be a new array
for i = n-1 to 0
if A[i..n-1] is a word in d
A[i] = [n]
else
A[i] = [] // Empty set
for j = i+1 to n-1
if A[j] == True and s[i..j-1] is a word in d
insert j to A[i]
return A

The next step is to print all possible sentences with breaks. In another word, we need to find all valid sequences of breaks. Before doing this, lets review the meaning of A[i]. A[i] dentoes the next valid break after setting a break before s[i]. That is, we cannot set a break after we setting a break before s[i] if A[i] is []; otherwise A[i] is a list of all valid breaks after setting break before s[i].

A valid sequence of breaks should be in the form of (0, b1, ..., bm, n). We can solve all possible sequences by using BFS which starts from A[0] which contains valid values of the first break and find all valid paths (a path ends with "n") and print the sentences with the breaks of the path.

The path is at most of length |s|=n, and for each break there are at most |d| possible choices, so the BFS could terminate in O(|d|^|n|) time. The following code is the python solution accepted by oj.leetcode.

class Solution:
# @param s, a string
# @param dict, a set of string
# @return a list of strings
def wordBreak(self, s, dict):
"""
We solve this problem using DP similar to the solution for word break I
Let A[0..n-1] be an array, instead of being boolean, each A[i] is list of
all possible j > i such that s[i..j-1] is a word and A[j] == True.
"""
# Step 1: similar to word break I,
# but A[i] is a list instead of a boolean value
n = len(s)
A = [None] * n
i = n-1
while i >= 0:
if s[i:n] in dict:
A[i] = [n] # A[i] contains "n" means s[i..n-1] is a word
else:
A[i] = []
# Check al possible j break
for j in xrange(i+1, n):
if A[j] and s[i:j] in dict:
A[i].append(j)
i -= 1 # Step 2: find all possible sequences of breaks,
# which equals to find all paths from A[0] and stop when the break is "n".
# So it converts to BFS on a graph, with at most n steps.
res = [] # possible sentences with break
path_list = [[0]] # initially, there is only one path containing the source node
while path_list:
new_list = []
# For each path,
# 1) If the path ends with break "n", then segment the string with breaks of the path
# 2) otherwise, expand it with all possible breaks
for path in path_list:
if path[-1] == n: # segment!
# Get words according to the breaks
temp = [ s[path[i]:path[i+1]] for i in xrange(len(path)-1) ]
# join words together
res.append(" ".join(temp))
else: # expand the path
for j in A[path[-1]]:
new_list.append(path+[j])
path_list = new_list
return res

【LeetCode OJ】Word Break II的更多相关文章

  1. 【LeetCode OJ】Word Ladder II

    Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...

  2. 【LeetCode OJ】Word Break

    Problem link: http://oj.leetcode.com/problems/word-break/ We solve this problem using Dynamic Progra ...

  3. 【LeetCode OJ】Word Ladder I

    Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...

  4. 【LeetCode OJ】Path Sum II

    Problem Link: http://oj.leetcode.com/problems/path-sum-ii/ The basic idea here is same to that of Pa ...

  5. 【LeetCode OJ】Palindrome Partitioning II

    Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning-ii/ We solve this problem by u ...

  6. 【LEETCODE OJ】Single Number II

    Problem link: http://oj.leetcode.com/problems/single-number-ii/ The problem seems like the Single Nu ...

  7. 【leetcode】Word Break II

    Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...

  8. 【LeetCode 229】Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...

  9. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

随机推荐

  1. NSException

    NSException是什么? 最熟悉的陌生人,这是我对NSException的概述,为什么这么说呢?其实很多开发者接触到NSException的频率非常频繁,但很多人都不知道什么是NSExcepti ...

  2. Android WebView的使用

    WebView是View的一个子类,使用它可以在App中嵌入H5页面,可以跟js互相调用. webview有两个方法:setWebChromeClient和setWebClient setWebCli ...

  3. Jquery 表格操作,记录分页情况下,每一页中被用户勾选的信息

    如下图,一个分页列表,用户可以随意勾选一条或多条信息,然后进行某种操作,如“提交”.但是有个问题:如果勾选了一条信息之后,点[下一页],那么上一页 勾选的条目被刷新掉了. 问题:如果用户需要在第1页, ...

  4. sed 替换

    sed -i 's/i=0/i=2/g' test2.sh -i 在当前文档替换 g 替换所有文档 sed -i '3s/cccc/ccccc/' a.txt 将第三行的 cccc 替换成 ccccc ...

  5. PHP Memcached应用实现代码

    一.memcached 简介 在很多场合,我们都会听到 memcached 这个名字,但很多同学只是听过,并没有用过或实际了解过,只知道它是一个很不错的东东.这里简单介绍一下,memcached 是高 ...

  6. 监听TelephonyManager的通话状态来监听手机的所有的来电

    import java.io.FileNotFoundException;import java.io.OutputStream;import java.io.PrintStream;import j ...

  7. Hduacm—5497

    #include <cstring> #include <cstdio> #include <iostream> using namespace std; type ...

  8. [Js]面向对象基础

    一.什么是对象 对象是一个整体,对对外提供一些操作 二.什么是面向对象 使用对象时,只关注对象提供的功能,不关注其内部细节,比如Jquery 三.Js中面向对象的特点 1.抽象:抓住核心问题 2.封装 ...

  9. bzoj 1856: [Scoi2010]字符串

    #include<cstdio> #include<iostream> #define Q 20100403 ; int main() { scanf("%lld%l ...

  10. Validform自定义提示效果-使用自定义弹出框

    $(function(){ $.Tipmsg.r=null; $("#add").Validform({ tiptype:function(msg){ layer.msg(msg) ...