首页 > 代码库 > Palindrome Partitioning II

Palindrome Partitioning II

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.

答案

public class Solution {
    public int minCut(String s)
    {
        int N=s.length();
        int minCuts[]=new int[N+1];
        int i;
        for(i=0;i<=N;i++)
        {
            minCuts[i]=i-1;
        }
        for(i=0;i<N;i++)
        {
            //odd
            for(int j=0;i-j>=0&&i+j<N&&s.charAt(i-j)==s.charAt(i+j);j++)
            {
                minCuts[i+j+1]=Math.min(minCuts[i+j+1], 1+minCuts[i-j]);
            }
            //even
            for(int j=1;i-j+1>=0&&i+j<N&&s.charAt(i-j+1)==s.charAt(i+j);j++)
            {
                minCuts[i+j+1]=Math.min(minCuts[i+j+1], 1+minCuts[i-j+1]);
            }
        }
        return minCuts[N];
    }
}


Palindrome Partitioning II