Problem Palindrome Partitioning II
Problem Description:
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.
Solution:
1 public int minCut(String s) { 2 int[] res = new int[s.length()]; 3 boolean[][] mp = new boolean[s.length()][s.length()]; 4 5 for (int i = s.length() -1; i >= 0; i--) { 6 for (int j = i; j < s.length(); j++) { 7 if (s.charAt(i) == s.charAt(j) && ((j - i) < 2 || mp[i+1][j-1])) { 8 mp[i][j] = true; 9 } else { 10 mp[i][j] = false; 11 } 12 } 13 } 14 15 for (int i = 0; i < s.length(); i++) { 16 int ms = s.length(); 17 if (mp[0][i]) { 18 res[i] = 0; 19 } else { 20 for (int j = 0; j < i; j++) { 21 if (mp[j+1][i] && ms > res[j] + 1) { 22 ms = res[j] + 1; 23 } 24 } 25 26 res[i] = ms; 27 } 28 } 29 30 return res[s.length() -1]; 31 }