Saturday, November 16, 2013

palindrome partitioning II@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career

Question:

Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

Analysis: 

The basic and straight forward solution of this problem is, find the palindrome of the string from the very start, once find one, get the minimum cut number of the rest string recursively. Use a vector to store the cut number and define a helper function to decide palindrome or not.

In this way, time limit exceed in huge test cases. 

There are 2 parts that cost too much time.
1. Used a helper function to decide palindrome every time.
2. Recursively call of function.

The normal improvement methods for these two aspects are
1. Define a vector to memorize the palindrome judging results and make use of them which saves time in repeating judging.

2. Use a iterative way to search through the whole solution space instead of recursion. 

We use DP here to solve the problem. DP works for many problem which asks for finding the optimal solution. 

To define the equation and relationship for the problem first.
For example, we have a string 

a a a a a a a a b b b a b b b
                      i           j

D[i] equals the minimum cut number for string [i,n].
Thus, D[i] = min(D[i], D[j+1]+1) j<=i, and [j+1, i] forms a palindrome.

Then how to decide whether a string is a palindrome with dp?

We define P[i][j] = true if [i,j] is a palindrome
P[i][j] = str[i]==str[j]&&(j-i<2||p[i+1][j-1])

p[i+1][j-1] means the center part of string forms a palindrome.
a    b   b   b   a
i   i+1     j-1  j

With these two DPs, we can solve this problem with optimal time cost.





1 comment:

  1. The logic shown in your code is sort of different from your analysis? "Thus, D[i] = min(D[i], D[j+1]+1) j<=i, and [j+1, i] forms a palindrome." in above sentence, it should be "j >= i" instead of "j <= i" and [i, j] forms a palindrome, right?

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...