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的更多相关文章

  1. 【LeetCode OJ】Palindrome Partitioning II

    Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning-ii/ We solve this problem by u ...

  2. 【LeetCode OJ】Interleaving String

    Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...

  3. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  4. LeetCode OJ:Palindrome Partitioning(回文排列)

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

  5. 【LeetCode OJ】Valid Palindrome

    Problem Link: http://oj.leetcode.com/problems/valid-palindrome/ The following two conditions would s ...

  6. 【LeetCode OJ】Validate Binary Search Tree

    Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...

  7. 【LeetCode OJ】Recover Binary Search Tree

    Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...

  8. 【LeetCode OJ】Same Tree

    Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepte ...

  9. 【LeetCode OJ】Symmetric Tree

    Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse ...

随机推荐

  1. HTML5自学笔记[ 16 ]canvas绘图基础3

    canvas还提供提供了一些动态方法,使图像可以旋转.缩放和移动,与css3中的方法一样. 移动:translate(x,y),x和y为横竖方向的偏移量 旋转:rotate(弧度),弧度=角度*Mat ...

  2. C#中结构体和类的区别

    结构体和类同样能够定义字段,方法和构造函数,都能实例化对象,这样看来结构体和类的功能好像是一样的了,但是他们在数据的存储上是不一样的 C#结构体和类的区别问题:这两种数据类型的本质区别主要是各自指向的 ...

  3. 《转》---使用递归方法DataTable 绑定 TreeView

    转自:http://blog.sina.com.cn/s/blog_8944756d01016yaj.html 前台: <asp:View ID="view0" runat= ...

  4. PHP 页面编码声明方法详解(header或meta)

    php的header来定义一个php页面为utf编码或GBK编码 php页面为utf编码 header("Content-type: text/html; charset=utf-8&quo ...

  5. NSString asscii格式(2进制) 转 utf8格式——解决iOS自己处理http socket数据,遇到Transfer-Encoding: chunked时

    因为需要实现自己的http客户端,就要自己模拟http 的socket通讯: 上行不难,自己处理好http即可. 但下行时,服务器端的动态语言返回数据有可能会是这种格式: http头 16进制表示的数 ...

  6. winform插入sql的事务处理

    实现目的:点击按钮,原子性执行两条sql语句,同时成功或同时失败 数据库有这三个字段(忽略已有的一条记录): 一.用事务的sql语句 按钮事件完整代码: //事务处理插入sql语句 using (SQ ...

  7. jsp中JavaBean的用法

    UserRegisterBean.java:这是JavaBean package JavaBean; public class UserRegisterBean { private String us ...

  8. validator

    http://rickharrison.github.io/validate.js/validate.js rules: 'required|callback_check_password' vali ...

  9. scikit-learn 机器学习工具包

    scikit-learn官网:http://scikit-learn.org/stable/ scikit-learn初始化学习:  http://scikit-learn.org/stable/in ...

  10. mysql中Access denied for user 'root'@'localhost' (using password:YES)(zhuan)

    错误代码 1045Access denied for user 'root'@'localhost' (using password:YES) 如果你的mysql也出现以上这种提示, 建议你逐个字看完 ...