JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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.

Example 1:

Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

Example 2:

Input: s = "a"
Output: 0

Example 3:

Input: s = "ab"
Output: 1

Code

class Solution {
    public int minCut(String s) {
        if(s == null || s.length() == 0) return 0;
        
        int len = s.length();
        int[] cuts = new int[len];
        boolean[][] isPal = new boolean[len][len];
        
        for(int i = 0; i < len; i++){
            // 一开始赋值为最多切多少刀
            int min = i;
            // 总要进入 j == i,为了更新isPal;同时得到cuts[j - 1] + 1的结果
            for(int j = 0; j <= i; j++){
                // 如果i <= j + 1那么并且s.charAt(i) == s.charAt(j),那就是字符串之中最小的回文
                // 通过这个第一个回文,可以计算出更长的回文
                if(s.charAt(i) == s.charAt(j) && (i == j + 1 || i == j || isPal[j + 1][i - 1])){
                    isPal[j][i] = true;
                    // 如果j = 0
                    // 相当于 abba这种情况,因此不需要切,直接返回0
                    // 否则证明当前的j - i是回文,
                    // 那么只要知道j之前是怎么切的,再多加一刀就是当前的切法了
                    // min是当前层最少切多少刀
                    min = Math.min(min, j == 0 ? 0 : 1 + cuts[j - 1]);
                }
            }
            cuts[i] = min;
        }
        
        return cuts[len - 1];
    }
}