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. WPF:xmal 静动态资源

    <StackPanel.Resources> <SolidColorBrush x:Key="myBrush" Color="Teal"/&g ...

  2. Spring配置文件解析--bean属性

    1.bean设置别名,多个别名用逗号隔开 <!--使用alias--> <bean id="app:dataSource" class="...&quo ...

  3. 多条查询sql语句返回多表数据集

    + + "';SELECT ProductID,ProductTitle,ProductName,SalePrice,ListingPrice,MainPicture,SaledItemCo ...

  4. poj3159 Candies(差分约束,dij+heap)

    poj3159 Candies 这题实质为裸的差分约束. 先看最短路模型:若d[v] >= d[u] + w, 则连边u->v,之后就变成了d[v] <= d[u] + w , 即d ...

  5. 《Play for Java》学习笔记(七)数据类型解析——Body parser

    一.什么是body parser? body parser(不知道具体如何翻译,~~~~(>_<)~~~~ )指一个HTTP请求 (如POST和PUT操作)所包含的文本内容(body),这 ...

  6. 使用Parallel

    Parallel是.net framework为我们封装的用于并行的静态类,它使用起来简单灵活.它为我们提供了三个方法,分别是Invoke,For和ForEach.下面来进行分别演示. Paralle ...

  7. php 采集类snoopy http://www.jb51.net/article/27568.htm | cURL、file_get_contents、snoopy.class.php 优缺点

    Snoopy是一个php类,用来模拟浏览器的功能,可以获取网页内容,发送表单. Snoopy的特点: 1.抓取网页的内容 fetch 2.抓取网页的文本内容 (去除HTML标签) fetchtext ...

  8. 【vmware vcp 5.1】安装及配置及笔记散记

    ESXi的几个命令技巧: ------------------------------------------------- alt-f1: 进入console alt-f2: 返回DCUI alt- ...

  9. java面向对象编程——第四章 类和对象

    OO:面向对象 OOP:面向对象编程 OOA:面向对象分析 OOD:面向对象设计 结构化编程:从顶向下,将一个大问题分解成更小的任务,然后为每一个更小的任务编写一个过程.最后程序员会编写一个主过程来启 ...

  10. 实现js中的重载

    重载是面向对象语言里很重要的一个特性,JS中没有真正的重载,是模拟出来的(因为js是基于对象的编程语言,不是纯面向对象的,它没有真正的多态:如继承.重载.重写) 一.什么时候用重载? 举例: func ...