【LeetCode OJ】Palindrome Partitioning
Problem Link:
http://oj.leetcode.com/problems/palindrome-partitioning/
We solve this problem using Dynamic Programming. The problem holds the property of optimal sub-strcuture. Assume S is a string that can be partitioned into palindromes w1, ..., wn. Then, we have a sub-string of S, S' = w1 + w2 + ... + wn-1, also can be partitioned into palindromes.
Let B[0..n-1] be an array, where B[i] is a list of valid breaks such that for a break position j s[0..i] = s[0..j-1] + s[j..i] where s[j..i] is a palindrome. Therefore, we have the recursive formula:
B[i] = [0] for s[0..i] is a palindrome
B[i] += { j | s[0..j-1] can be partitioned into palindromes and s[j..i] is a palindrome, j =1, ..., i }
To check if s[j..i] is a palindrome in O(1) time, we ultilize a 2D array to keep track of whether s[j..i] is palindrome or not. It takes O(n2) space and O(n2) time to compute each P[j][i].
To find all possible breaks, we start from the end of the string. All possible "last break" are in B[n-1], if B[n-1] is empty then there is no possible squence of breaks. If x in B[n-1], then we continue to find all possible breaks for string s[0..B[n-1]-1] and add the x to the end of all possible sequences of breaks. This process will continue recursively until all possible sequences have 0 as the first break.
The following code is the python code accepted by oj.leetcode.com.
class Solution:
# @param s, a string
# @return a list of lists of string
def partition(self, s):
"""
Input: a string s[0..n-1], where n = len(s) DP solution: use an array B[0..n-1]
B[i] presents a list of break positions for string s[0..i].
In the list B[i], each break position j (0 < j < i) means
s[0..i] = s[0..j-1] + s[j..i] where s[0..j] can be partitioned
into palindromes and s[j+1..i] is a palindrome.
Note that B[i]=[] means s[0..i] cannot be partitioned into palindromes,
and 0 in B[i] means s[0..i] is a palindrome. Additional we may need a 2D boolean array P[0..n-1][0..n-1] to tell if s[i..j-1] is a palindromes
"""
n = len(s)
# Special case: s is ""
if n == 0:
return [] # P[i][j] denotes whether s[i..j] is a palindrome
P = []
for _ in xrange(n):
P.append([False]*n)
# Compute P[][], T(n) = O(n^2) and S(n) = O(n^2)
for mid in xrange(n):
P[mid][mid] = True
# Check strings with the mid of s[mid]
i = mid - 1
j = mid + 1
while i >= 0 and j < n and s[i] == s[j]:
P[i][j] = True
i -= 1
j += 1
# Check strings with mid "s[mid]s[mid+1]"
i = mid
j = mid + 1
while i >= 0 and j < n and s[i] == s[j]:
P[i][j] = True
i -= 1
j += 1 # Compute B[]
B = [None] * n
for i in xrange(0, n):
if P[0][i]:
B[i] = [0]
else:
B[i] = []
# s[0 .. i] = s[0 .. j-1] + s[j .. i]
j = 1
while j <= i:
if B[j-1] != [] and P[j][i]:
B[i].append(j)
j += 1 # BFS in the graph
res = []
# Last breaks
breaks = [ [x, n] for x in B[n-1] ]
while breaks:
temp = []
for lst in breaks:
if lst[0] == 0:
res.append([ s[lst[i]:lst[i+1]] for i in xrange(len(lst)-1) ])
else:
# s[0..i] = s[0..j-1] + s[j..i]
for j in B[lst[0]-1]:
temp.append([j]+lst)
breaks = temp
return res
【LeetCode OJ】Palindrome Partitioning的更多相关文章
- 【LeetCode OJ】Palindrome Partitioning II
Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning-ii/ We solve this problem by u ...
- 【LeetCode OJ】Interleaving String
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
- LeetCode OJ:Palindrome Partitioning(回文排列)
Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...
- 【LeetCode OJ】Valid Palindrome
Problem Link: http://oj.leetcode.com/problems/valid-palindrome/ The following two conditions would s ...
- 【LeetCode OJ】Validate Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...
- 【LeetCode OJ】Recover Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...
- 【LeetCode OJ】Same Tree
Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepte ...
- 【LeetCode OJ】Symmetric Tree
Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse ...
随机推荐
- HDUOJ 2672---god is a girl 《斐波那契数》
god is a girl Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) To ...
- struts过滤器和拦截器的区别
拦截器的工作原理:当接收到一个httprequest ,a) 当外部的httpservletrequest到来时 b) 初始到了servlet容器 传递给一个标准的过滤器链 c) FilterDisp ...
- UB单修改
FUNCTION Z_SD_UB_CHANGE. *"-------------------------------------------------------------------- ...
- Excel VBA记录
-----------快捷键---------- 函数等提示(默认):ctrl+j 注释:上单引号' 设置单元格为空可以用:empty/null -----------基础语法--------- 基本 ...
- PDF 补丁丁 0.4.2.891 测试版发布:合并PDF文件时设置书签文本和样式
新的测试版在合并文件界面增加了设置书签样式的功能.除了可以为所合并的图片(或PDF文件)指定书签文本之外,还可以指定其文本样式(文本颜色.粗体.斜体).如下图所示. 此外,合并文件界面还添加了文件夹历 ...
- ios下input focus弹出软键盘造成fixed元素位置移位
正常状态下 input focus软键盘弹出时 问题描述: 头部结构fixed,滚动到下部内容区域,input.textarea等focus弹出软键盘时,头部位置偏移被居中(该问题ios7 beta3 ...
- Memcached 及 Redis 架构分析和比较
Memcached和Redis作为两种Inmemory的key-value数据库,在设计和思想方面有着很多共通的地方,功能和应用方面在很多场合下(作为分布式缓存服务器使用等) 也很相似,在这里把两者放 ...
- js unix时间戳转换
一.unix时间戳转普通时间: var unixtime=1358932051; var unixTimestamp = new Date(unixtime* 1000); commonTime = ...
- CRF++使用小结
1. 简述 最近要应用CRF模型,进行序列识别.选用了CRF++工具包,具体来说是在VS2008的C#环境下,使用CRF++的windows版本.本文总结一下了解到的和CRF++工具包相关的信息. 参 ...
- Hibernate中的集合映射
1.定义实体 public class User { private int userId; private String userName; private Set<String> ad ...