【题目】
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]; } }
时间: 2024-10-23 15:02:41