【LeetCode】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.

【分析】

问题:求字符串的最小分割数,使得分割后的子串都是回文串。

动态规划的关键是找出动规方程:cutNum[i] = min(cutNum[i], cutNum[j + 1] + 1)

cuntNum[i] 表示字符串 s 从 i 到末尾的子串所需要的最小割数,如果从 i 到 j 的子串为回文串的话,那么最小割数就可能为 j + 1以后的子串的最小割数加上 j 和 j + 1 之间的一割。

【反向动规解法】

public class Solution {
    public int minCut(String s) {
    	if (s == null || s.length() < 2) return 0;
        
        int n = s.length();
        boolean[][] isPalin = new boolean[n][n]; // isPalin[i][j]: is palindrome from i to j
        int[] cutNum = new int[n]; // cutNum[i]: cuts numbers from i to end
        
        for (int i = n - 1; i >= 0; i--) {
            cutNum[i] = n - 1 - i;
            
            for (int j = i; j < n; j++) {
                if (s.charAt(i) == s.charAt(j) && (j - i < 2 || isPalin[i + 1][j - 1]) ) {
                    isPalin[i][j] = true;
                    
                    if (j == n - 1) {
                        cutNum[i] = 0; // s[i...n-1] is palindrome, no need cut
                    } else {
                        cutNum[i] = Math.min(cutNum[i], cutNum[j + 1] + 1);
                    }
                }
            }
        }
        
        return cutNum[0];
    }
}

可能有人对这种从后往前的方式不太习惯,那么可以看下面从前往后的动规方法。

【正向动规解法】

public class Solution {
    public int minCut(String s) {
    	if (s == null || s.length() < 2) return 0;
        
        int n = s.length();
        boolean[][] isPalin = new boolean[n][n]; // isPalin[i][j]: is palindrome from i to j
        int[] cutNum = new int[n]; // cutNum[i]: cuts numbers from 0 to i
        
        for (int i = 0; i < n; i++) {
            cutNum[i] = i;
            
            for (int j = i; j >= 0; j--) {
                if (s.charAt(j) == s.charAt(i) && (i - j < 2 || isPalin[j + 1][i - 1]) ) {
                    isPalin[j][i] = true;
                    
                    if (j == 0) {
                        cutNum[i] = 0; // s[0...i] is palindrome, no need cut
                    } else {
                        cutNum[i] = Math.min(cutNum[i], cutNum[j - 1] + 1);
                    }
                }
            }
        }
        
        return cutNum[n - 1];
    }
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值