【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 ...
随机推荐
- 笔记2:傻瓜式盗QQ程序
1.一个简单的盗QQ号的方法 仿做一个QQ的窗体 PS:当然里面有用的控件只有两个输入框和一个登陆按钮,其他的尽量做得像一些吧! 点登陆时的后台代码: PS:需要导入两个包:using System. ...
- 杂谈:Servlet(2)
Servlet的方法剖析: 1.service()方法里面做了什么? 2.doGet()与doPost()做了什么?应该怎么写? 回答 1.service()方法里面做了什么? 如果你的service ...
- poj------(3468)A Simple Problem with Integers(区间更新)
A Simple Problem with Integers Time Limit: 5000MS Memory Limit: 131072K Total Submissions: 60745 ...
- Ajax请求中带有IPv6地址后的百分号的问题
IPv6地址后的百分号: 对于连入网络但没有IPv6路由器或DHCPv6服务器的IPv6客户端,它们始终使用fe80::/64链路本地网络地址.如果运行Windows的计算机中有多个网络适配器连接到不 ...
- Android实现Activity页面跳转切换动画特效
了解Android程序设计的人应该知道,在Android 2.0之后有了overridePendingTransition(),其中里面两个参数,一个是前一个activity的退出,另一个activi ...
- Spring事务管理中@Transactional
最近写的一个消息推送的接口,供订单生成后调用,发现每次传过来的时候订单id是存在的,可是利用订单id去查订单信息做后续操作时发现查不到数据,最终发现是订单生成时候业务处理写在service层,加了Sp ...
- 怎么实现form表单提交后不重新刷新当前页面
怎么实现表单提交后不重新刷新当前页面 如何实现表单提交后不重新刷新当前页面 <form name='form1' id='form1' action='/xbcw/cw/xx_xx.ac ...
- 解决qt5在ubuntu下无法调用fcitx输入中文的问题
如题,在以前安装qt5.2.1的时候就遇到了这个问题.当时上网搜了很多资料,结果都解决不了,发现都是复制来复制去. 这次因为要用qt5.3.0在ubuntu下写个程序,所以不解决这个问题不行了.就继续 ...
- easyui datagrid 学习
一.清空datagrid所有数据 //得到所有数据行 var item = $('#ylProductListDataGrid').datagrid('getRows'); if (item) { / ...
- C#WPF做FTP上传下载获取文件列表
Xaml.cs: using Microsoft.Win32;using System;using System.Collections.Generic;using System.IO;using S ...