Java for LeetCode 132 Palindrome Partitioning II

时间:2021-09-18 13:55:12

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.

解题思路:

因为是Hard,用上题的结果计算肯定是超时的,本题需要用dp的思路,开一个boolean[][]的数组计算i-j是否为palindrome,递推关系为s.charAt(j) == s.charAt(i) &&  isPal[j + 1][i - 1]) → isPal[j][i] = true,同时dp[i] = Math.min(dp[i], dp[j - 1] + 1),JAVA实现如下:

    public int minCut(String s) {
int[] dp = new int[s.length()];
for (int i = 0; i < dp.length; i++)
dp[i] = i;
boolean isPal[][] = new boolean[s.length()][s.length()];
for (int i = 1; i < s.length(); i++)
for (int j = i; j >= 0; j--)
if (s.charAt(j) == s.charAt(i)
&& (j + 1 >= i - 1 || isPal[j + 1][i - 1])) {
isPal[j][i] = true;
dp[i] = j == 0 ? 0 : Math.min(dp[i], dp[j - 1] + 1);
}
return dp[dp.length - 1];
}