132. Palindrome Partitioning II

来源:互联网 发布:网络编辑简历模板 编辑:程序博客网 时间:2024/05/22 17:01

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 ofs.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.


思路: 一个字符串s(i,j)是回文,当且仅当s[i]=s[j]且s(i+1,j-1)也是回文串;或者s[i]=s[j]且i+1>j-1(1歌或2个元素的情况);

字符串分割的最小次数s(0,i)其等于min(s(0,j-1)+1) (0=<j<=i) 当且仅当s(j,i)是回文串,当j=0时,切分次数为0。

时间/空间复杂度:O(N×N)


<span style="font-size:14px;">public class Solution {    public int minCut(String s) {        if(s==null)            return 0;        int n=s.length();        if(n<=1)            return 0;        int[] cut=new int[n];        boolean[][] flag=new boolean[n][n];        int min;        for(int i=0;i<n;i++){            min=i;//the max cut numbers            for(int j=0;j<=i;j++){                if(s.charAt(i)==s.charAt(j)&&((j+1)>(i-1)||flag[j+1][i-1])){                    flag[j][i]=true;                    if(j==0)                        min=0;                    else                        min=min<(cut[j-1]+1)?min:(cut[j-1]+1);                }            }            cut[i]=min;        }        return cut[n-1];    }}</span>



0 0