Skip to content

Instantly share code, notes, and snippets.

@hilda8519
Created November 9, 2014 22:26
Show Gist options
  • Save hilda8519/f564b4f7b33da3183c21 to your computer and use it in GitHub Desktop.
Save hilda8519/f564b4f7b33da3183c21 to your computer and use it in GitHub Desktop.
public class Solution {
public int minCut(String s) {
int n = s.length();
boolean[][] isPalindrome = new boolean[n][n];
for (int i = 0; i < n; i++)
isPalindrome[i][i] = true;
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (s.charAt(i) == s.charAt(j)) {
if (j - i < 2 || isPalindrome[i + 1][j - 1])
isPalindrome[i][j] = true;
}
}
}
int[] minCut = new int[n + 1];
for (int i = n; i >= 0; i--)
minCut[i] = n - 1 - i;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (isPalindrome[i][j]) {
minCut[i] = Math.min(minCut[i], 1 + minCut[j + 1]);
}
}
}
return minCut[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment