Leetcode 132: Palindrome Partitioning II
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.
1 public class Solution { 2 public int MinCut(string s) { 3 int len = s.Length; 4 if (len < 2) return 0; 5 6 int[] cut = new int[len]; 7 bool[,] dp = new bool[len, len]; 8 9 for (int j = 0; j < len; j++) 10 { 11 for (int i = 0; i < len; i++) 12 { 13 if (i >= j || (s[i] == s[j] && dp[i + 1, j - 1])) 14 { 15 dp[i, j] = true; 16 } 17 } 18 } 19 20 for (int j = 0; j < len; j++) 21 { 22 cut[j] = j; 23 for (int i = 0; i <= j; i++) 24 { 25 if (dp[i, j]) 26 { 27 cut[j] = Math.Min(cut[j], i > 0 ? (cut[i - 1] + 1) : 0); 28 } 29 } 30 } 31 32 return cut[len - 1]; 33 } 34 }