【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 ...
随机推荐
- Qt之QCustomPlot(图形库)
简述 QCustomPlot是一个基于Qt C++的图形库,用于绘制和数据可视化 - 制作漂亮的2D图 - 曲线图.趋势图.坐标图.柱状图等,并为实时可视化应用程序提供高性能服务.它没有进一步的依赖关 ...
- python中的异常处理
主要用到 try...except...raise...finally... 1. try...except... try: for i in range(1, 1000): print i time ...
- hdu------(1525)Euclid's Game(博弈决策树)
Euclid's Game Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Tot ...
- 南阳OJ----Binary String Matching
Binary String Matching 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 Given two strings A and B, whose alp ...
- 【转载】Gambit使用教程
第一章 Gambit使用 Gambit介绍 网格的划分使用Gambit软件,首先要启动Gambit,在Dos下输入Gambit <filemane>,文件名如果已经存在,要加上参数-old ...
- CSS3 Media Queries
Media Queries直译过来就是“媒体查询”,在我们平时的Web页面中head部分常看到这样的一段代码: <link href="css/reset.css" rel= ...
- 使用Yeoman,Grunt和Bower开发AngularJS(译)
使用Yeoman产生AngularJS的主要骨架 使用Grunt加速开发和帮助执行 使用Bower来加入第三方插件和框架——third party plugins/frameworks 一.准备工作 ...
- linux命令备份
sort -t $'\t' gcc版本查看 gcc -v 红帽版本查看 cat /etc/redhat-release Linux Core Version cat /proc/version
- Oozie简介
在Hadoop中执行的任务有时候需要把多个Map/Reduce作业连接到一起,这样才能够达到目的.[1]在Hadoop生态圈中,有一种相对比较新的组件叫做Oozie[2],它让我们可以把多个Map/R ...
- [css3]文字过多以省略号显示
text-overflow:ellipsis; 优点: 1.不用通过程序限定字数 2.有利于SEO(实际上并未被截字,只是局限于宽度未被显示而已) width: 某个值; overflow: hidd ...