LintCode Palindrome Partitioning II
Given a string s, cut s into some substrings such that every substring is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Given s = "aab",
Return 1 since the palindrome partitioning ["aa", "b"] could be produced using 1 cut.
For this problem, the minimum cuts to achieve all single palindrome words could be defined as f[n]. To solve this problem, the dynamic programming is needed to be used. For any integer from 0 to i-1, the f[i] is depend on the minimum value of f[j] + 1 becuase if there any value less than it will update it.
1 public class Solution { 2 /** 3 * @param s a string 4 * @return an integer 5 */ 6 public int minCut(String s) { 7 if (s==null || s.length() == 0 ) { 8 return 0; 9 } 10 int n = s.length(); 11 //preprocessing to store all the sub-string's boolean palindrome feature 12 boolean[][] isPalindrome = getIsPalindorme(s); 13 int[] f = new int[n+1]; 14 //initialize 15 for (int i =0; i <= n; i++) { 16 f[i] = i-1; 17 } 18 //DP 19 for (int i = 1; i <= n; i++) { 20 for (int j = 0; j < i; j++ ) { 21 if (isPalindrome[j][i-1]) { 22 f[i] = Math.min(f[i],f[j]+1); 23 } 24 } 25 } 26 return f[n]; 27 } 28 //this method is used to preprocess the result whether it is a panlindrome string of 29 //the certain substring from index i to index j and store them all into a matrix 30 public boolean[][] getIsPalindorme(String s) { 31 int length = s.length(); 32 boolean [][] isPalindrome = new boolean[length][length]; 33 //initialize for all single characters 34 for (int i = 0; i < length; i++) { 35 //this means all the single character in the string could be used as 36 //a palindrome word 37 isPalindrome[i][i] = true; 38 } 39 //initialize for all two neighbor characters 40 for (int i = 0; i < length-1; i++) { 41 isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1)); 42 } 43 //develop for all result from start to start + lengthj indexs subtring 44 for (int delta = 2; delta <= length -1; delta++) { 45 for (int start = 0; start + delta < length; start++) { 46 //the result of the string from index start to start+length 47 //is based on the result of string with index start+1 to start+length-1 48 //and and the two chars at start indexa and start +length index are equal 49 isPalindrome[start][start + delta] 50 = isPalindrome[start + 1][start + delta - 1] && s.charAt(start) == s.charAt(start + delta); 51 } 52 } 53 return isPalindrome; 54 } 55 }
浙公网安备 33010602011771号