码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Partitioning II

时间:2014-10-06 12:12:00      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   ar   java   for   sp   div   art   

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

标签:style   color   io   ar   java   for   sp   div   art   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39827055

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!