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. HDU-----(1083)Courses(最大匹配)

    Courses Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total S ...

  2. poj-----(2828)Buy Tickets(线段树单点更新)

    Buy Tickets Time Limit: 4000MS   Memory Limit: 65536K Total Submissions: 12930   Accepted: 6412 Desc ...

  3. HDUOJ-------1052Tian Ji -- The Horse Racing(田忌赛马)

    Tian Ji -- The Horse Racing Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (J ...

  4. uva-----11292 The Dragon of Loowater

    Problem C: The Dragon of Loowater Once upon a time, in the Kingdom of Loowater, a minor nuisance tur ...

  5. python的一点小常识

    在Python中,有两种变长参数,分别是元组(非关键字参数)和字典(关键字参数),其参数以一个*开头表示任意长度的元组[tuple],可以接收连续一串参数,参数以两个*开头表示一个字典[dict],即 ...

  6. apache rewrite设置 禁止某个文件夹执行php文件

    RewriteRule (data|templates)/(.*).(php)$ – [F]

  7. memached 服务器lru算法

    1.LRU是Least Recently Used的缩写,即最近最少使用页面置换算法,是为虚拟页式存储管理服务的.LRU算法的提出,是基于这样一个事实:在前面几条指令中使用频繁的页面很可能在后面的几条 ...

  8. java之io之file类的常用操作

    java io 中,file类是必须掌握的.它的常用api用法见实例. package com.westward.io; import java.io.File; import java.io.IOE ...

  9. (转)onTouchEvent方法的使用

      (转)onTouchEvent方法的使用 手机屏幕事件的处理方法onTouchEvent.该方法在View类中的定义,并且所有的View子类全部重写了该方法,应用程序可以通过该方法处理手机屏幕的触 ...

  10. JavaScript自定义右键菜单

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...