题目
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"
,
Return1
since the palindrome partitioning["aa","b"]
could be produced using 1 cut.
方法
使用DP思想
先求解 i-j的字串是不是回文串,并将结果放入一个二维数组中去。
创建一个长度为字符串长度为n的数组dis,dis[k]:表示0-k字串的最小划分。
从0到n-1计算dis数组。
boolean[][] palindromeArray(String s) { int len = s.length(); boolean[][] arrayPal = new boolean[len][len]; for (int interval = 0; interval < len; interval++) { for (int i = 0; i < len - interval; i++) { int j = i + interval; if (i == j){ arrayPal[i][j] = true; } else if (s.charAt(i) == s.charAt(j)) { if (j == i + 1) { arrayPal[i][j] = true; } else if (arrayPal[i + 1][j - 1] == true) { arrayPal[i][j] = true; } else { arrayPal[i][j] = false; } } else { arrayPal[i][j] = false; } } } return arrayPal; } public int minCut(String s) { if (s == null) { return -1; } else if (s.length() == 0){ return 0; } else if (s.length() == 1) { return 0; } else { int len = s.length(); boolean[][] status = palindromeArray(s); int[] dis = new int[len]; for (int i = 0; i < len; i++) { dis[i] = i; } for (int i = 1; i < len; i++) { if (status[0][i] == true) { dis[i] = 0; } else { for (int j = i; j > 0; j--) { if (status[j][i] == true) { int temp = dis[j - 1] + 1; if (temp < dis[i]) { dis[i] = temp; } } } } } return dis[len - 1]; } }