`

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.

给定一个字符串s,用最少的次数将它拆分成多个回文子串。我们用动态规划来解决。首先我们用一个二维的布尔数组isPalin[][]记录当前子串是否是回文串,例如isPalin[i][j] = true,就代表了字符串中从字符i到字符j是回文子串。(当s.charAt(i) == s.charAt(j)并且i + 1 >= j - 1的时候,也就是对应了’aa‘和’a?a‘这两种情况,此时肯定为回文串)。用数组dp[]来记录每个阶段的最小值,如果检测到从第一个字符到当前字符为回文子串,那么dp[j] = 0, 因为不需要拆分所以为0; 如果从字符i开始到当前字符为回文子串并且i > 0,此时dp[j] = dp[i - 1] + 1。实现代码如下:
public class Solution {
    public int minCut(String s) {
        if(s == null) return 0;
        boolean[][] isPalin = new boolean[s.length()][s.length()];
        int[] dp = new int[s.length()];
        for(int i = 0; i < dp.length; i++) {
            int min = i;
            for(int j = 0; j <= i; j++) {
                if(s.charAt(j) == s.charAt(i) && (j + 1 >= i - 1 || isPalin[j + 1][i - 1])) {
                    isPalin[j][i] = true;
                    min = (j == 0) ? 0 : Math.min(min, dp[j - 1] + 1);
                }
            }
            dp[i] = min;
        }
        return dp[s.length() - 1];
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics