Palindrome Partitioning II

来源:互联网 发布:淘宝神店 知乎 编辑:程序博客网 时间:2024/06/08 06:26

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.

Show Tags

Have you met this question in a real interview?


思路:

如果dfs,没有成功,timeout。只能用dp了。

利用一维DP.

cut[n] 代表 first k character cut num, 也就是说,代表index左边的string的最小cut数。

所以return的时候,要return cut[n] 从0 到n,所以int size是n+1

然后跟Longest palindrome 一样,用奇数偶数的对称中心来计算。

i - j    i   i +j   odd

i - j ....i - 1  i   i+1  i+2 ... i +j +1  even


递推公式为:

cut(i+j+1) = min( cut(i+j+1), 1+ cut(i-j) )

cut(j+j+1+1) = min( cut(i+j+1+1) , 1+ cut(i-j) )

记住:cut[i] 代表 i 左边的 0~i-1 的string的最小cut 不包括i本身

这样就好理解递推公式了。


我是看的:https://oj.leetcode.com/discuss/9476/solution-does-not-need-table-palindrome-right-uses-only-space.

这里只给了代码,我自己理解画图推理的。

这题要跟 Longest palindrome http://blog.csdn.net/u013325815/article/details/18922975 对应起来看。


public class Solution {    public int minCut(String s) {     int n = s.length();     int[] cut = new int[n+1]; // first k characters min cuts; index left side string, min cuts;     for(int i = 0; i<=n; i++){         cut[i]=i-1;     }          for(int i =0; i<n; i++){         // odd length palidrome;         for(int j=0; i-j>=0 && i+j<n && s.charAt(i-j) == s.charAt(i+j); j++){             cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j]);         }                  //even length palidrome;         for(int j=0; i-j>=0 && i+j+1<n && s.charAt(i-j) == s.charAt(i+j+1); j++){             cut[i+j+1+1] = Math.min(cut[i+j+1+1],1+cut[i-j]);         }     }     return cut[n];    }}








 

0 0
原创粉丝点击