leetcode原題--將字符串切割爲若干迴文子串的最小切割次數

leetcode題目: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”,
Return1since the palindrome partitioning[“aa”,”b”]could be produced using 1 cut.
Tag:動態規劃

public class Solution {
      /**
     * 迴文的最小分割數
     * 1.dp[i]表示當前i到len-1這段的最小分割數
     * 2.dp[i]=min{dp[j+1]+1}(i=<j<len)其中str[i..j]必須是迴文、
     * 3.p[i][j]=true表示str[i..j]是迴文
     * 4.p[i][j]=s.charAt(i)==s.charAt(j) && (j-i<2||p[i+1][j-1])
     */
    public int minCut(String s) 
    {
        int []dp=new int[s.length()+1];
        boolean [][]p=new boolean[s.length()][s.length()];
        dp[s.length()]=-1;//確保dp[s.length()-1]=0
        for(int i=s.length()-1;i>=0;i--)
        {
            dp[i]=Integer.MAX_VALUE;
            for(int j=i;j<s.length();j++)
            {
                if(s.charAt(i)==s.charAt(j) && (j-i<2||p[i+1][j-1]))
                {
                    p[i][j]=true;
                    dp[i]=Math.min(dp[i],dp[j+1]+1);
                }
            }
        }
        return dp[0];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章