Integer memo[][];
public boolean isValidPalindrome(String s, int k) {
if (s == null || s.length() == 0 || k < 0) {
return false;
}
memo = new Integer[s.length()][s.length()];
int parEditDistance = editDistanceForPar(s, 0, s.length() - 1);
return parEditDistance <= k;
}
private int editDistanceForPar(String s, int i, int j) {
// single char, no edit
if (i == j) {
return 0;
}
// two chars, if equal no edit, if not equal edit 1
if (i == j - 1) {
return s.charAt(i) == s.charAt(j) ? 0 : 1;
}
// after base cases, check if we've already computed this range
if (memo[i][j] != null) {
return memo[i][j];
}
// if 2 char equals, we check the content in between
if (s.charAt(i) == s.charAt(j)) {
return editDistanceForPar(s, i + 1, j - 1);
}
// if 2 chars are not equal,
// we removeLeft or removeRight, then check the contents
int removeLeft = editDistanceForPar(s, i + 1, j);
int removeRight = editDistanceForPar(s, i, j - 1);
// at the end, we would like to return the smallest edit distance
// use memo[][] to remember what we did
memo[i][j] = 1 + Math.min(removeLeft, removeRight);
return 1 + Math.min(removeLeft, removeRight);
}