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 ...
随机推荐
-
面试题_66_to_75_Java IO 和 NIO 的面试题
IO 是 Java 面试中一个非常重要的点.你应该很好掌握 Java IO,NIO,NIO2 以及与操作系统,磁盘 IO 相关的基础知识.下面是 Java IO 中经常问的问题. 66)在我 Java ...
-
使用WDS安装Windows8.1
WDS的部署 安装角色 配置 1. 选择配置服务器 2. 核对是否满足要求 3. 输入远程安装文件夹的路径 4. 选择是否使用自带的DHCP服务器 5. 可以保持默认 6. 完成配置后添加映像文件 7 ...
-
activitie用户手册
最近公司开发流程,学习流程开发,不停看api学习.这是做软件的额...不停的学习学习!!!天天进步中! 用户手册地址:http://www.mossle.com/docs/activiti/#acti ...
-
Entity Framework相关介绍
在深入学习某项技术之前,应该努力形成对此技术的总体印象,并了解其基本原理,本文的目的就在于此. 一.理解EF数据模型 EF本质上是一个ORM框架,它需要把对象映射到底层数据库中的表,为此,它使用了三个 ...
-
nginx启动停止
nginx -s reload :修改配置后重新加载生效 nginx -s reopen :重新打开日志文件 nginx -t -c /path/to/nginx.conf 测试nginx配置文件是否 ...
-
Python爬虫4-URLError与HTTPError
GitHub代码练习地址:URLError:https://github.com/Neo-ML/PythonPractice/blob/master/SpiderPrac06_URLError.py ...
-
环境搭建 - Tomcat(Windows)
Tomcat环境搭建 本文以Windows7下搭建tomcat-8.5.15为示例 下载tomcat压缩包 网址:Tomcat 非C盘根目录新建文件夹:Tomcat D:\tomcat 将tomcat ...
-
JavaScript-DOM(2)
内部样式及外部样式的获取及修改 内部样式或外部样式不能通过style属性获取样式 IE浏览器:var width = div1.currentStyle.width; 非IE:window.getCo ...
-
python爬虫解析页面数据的三种方式
re模块 re.S表示匹配单行 re.M表示匹配多行 使用re模块提取图片url,下载所有糗事百科中的图片 普通版 import requests import re import os if not ...
-
Java学习笔记(二十):多态
什么是多态 多态的好处 举个例子:需求:给饲养员提供一个喂养动物的方法,用于喂养动物 假如没有多态,会发现针对不同类型的动物,我们需要提供不同的feed方法来喂养,当需求变化时,比如增加动物,就要增加 ...