【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之坐标系统
简述 坐标系统是由QPainter类控制的,再加上QPaintDevice和QPaintEngine类,就形成了Qt的绘图体系. QPainter:用于执行绘图操作. QPaintDevice:二维空 ...
- hdu----(2222)Keywords Search(ac自动机)
Keywords Search Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)T ...
- hdu---(1325)Is It A Tree?(并查集)
Is It A Tree? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Tot ...
- java 多线程——quartz 定时调度的例子
java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...
- DataProcessing
clear load X4058 [m,n]=size(X528); Mean=zeros(1,n); Dev=zeros(1,n); for i=1:n Xi=X528(1:end-1,i); Xi ...
- JFrame背景
1.引言 在了解了JFrame面板的相关知识后,我们可以选择在RootPane根面板或LayeredPane面板中设置背景图案. 2.方法 对于大小固定的窗口背景设置如下: //导入图案 ImageI ...
- SqlFunctions 可以在EF种调用sqlserver的函数
在EF5环境下,首先添加EF环境,在引用中添加Syste.Data.Entity,再添加命名空间 using System.Data.Objects.SqlClient; 然后写一个控制器测试 pub ...
- linux系统字符集
Linux中中文乱码问题通常是由于字符集与windows不兼容所引起,windows的中文字符集是双字节的GBK编码linux采用的是3字节的utf-8编码,所以在windows下用工具连接linux ...
- Android 获取网络状态
1.检测网络是否可用 public boolean isNetWorkConnected() { ConnectivityManager cm = (ConnectivityManager)getSy ...
- ppurl
ppurl 就这么挂了?? 简直不敢相信 我才刚上不久,它竟然就这么挂啦??? 还是转到哪了? 有人知道吗? 表示我很愤怒,就好像当年新浪爱问共享就这么挂了一样 过了很久我才知道原来它转到新浪微盘了. ...