【LeetCode OJ】Word Break II
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的更多相关文章
- 【LeetCode OJ】Word Ladder II
Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...
- 【LeetCode OJ】Word Break
Problem link: http://oj.leetcode.com/problems/word-break/ We solve this problem using Dynamic Progra ...
- 【LeetCode OJ】Word Ladder I
Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...
- 【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 ...
- 【LeetCode OJ】Palindrome Partitioning II
Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning-ii/ We solve this problem by u ...
- 【LEETCODE OJ】Single Number II
Problem link: http://oj.leetcode.com/problems/single-number-ii/ The problem seems like the Single Nu ...
- 【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 ...
- 【LeetCode 229】Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
随机推荐
- hdu----(4301)Divide Chocolate(状态打表)
多校综合排名前25名的学校请发送邮件到HDUACM@QQ.COM,告知转账信息(支付宝或者卡号) Divide Chocolate Time Limit: 2000/1000 MS (Java/Oth ...
- App crash 报错 'NSUnknownKeyException'
报错: *** Terminating app due to uncaught exception , reason: '[<NSObject 0x6e36ae0> setValue:fo ...
- 新建txt文件新增内容并打印出
#!/usr/bin/python import os file1=open("C:\Python34\ceshi.txt","a+"); #a+开一个文件用 ...
- Web总结
Web总结 学习web前端理论基础必然是要过关的,这里我总结了一下比较基础的常用理论,还是比较有用哒! 一.名词解释 1.横切 在固定页面的宽度(按栅格化进行)并且对高度没有限制的容器称为一个标准横切 ...
- HDU4815
Little Tiger vs. Deep Monkey Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/65535 K ( ...
- E-Eating Together(POJ 3670)
Eating Together Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 5579 Accepted: 2713 D ...
- thinkjs——修改where默认条件为or
写之前,得先反思一下:总以为大神同事的高冷是一种与大家格格不入的节奏,可是当自己遇到的问题难以解决的时候,大神同事一下子就让问题迎刃而解,于是,满眼的敬佩之感:一定努力当一个像大神同事一样的progr ...
- 关于JDBC
脑补一下JDBC基础知识,原文链接:http://docs.oracle.com/javase/tutorial/jdbc/basics/gettingstarted.html If you are ...
- BZOJ1932 [Shoi2007]Setstack 集合堆栈机
妈呀...clj大爷太强啦! 原来还有set_union和set_intersection这种东西... 于是只要把栈顶的每个元素hash一下记录到一个vector里去就好了 /*********** ...
- 表单form的属性,单行文本框、密码框、单选多选按钮
基础表单结构: <body> <h1> <hr /> <form action="" name="myFrom" en ...