classSolution { publicintminimumChanges(String s, int k) { intn= s.length();
int[][] change = newint[n][n]; for (inti=0; i < n - 1; i++) { for (intj= i + 1; j < n; j++) { change[i][j] = calc(s.substring(i, j + 1)); } }
int[][] dp = newint[n][k]; for (inti=0; i < n; i++) { Arrays.fill(dp[i], -1); } return dfs(0, s, n, k - 1, change, dp); }
privateintcalc(String s) { intn= s.length(), res = n; for (intd=1; d < n; d++) { if (n % d == 0) { intcnt=0; for (intk=0; k < d; k++) { for (inti= k, j = n - d + k; i < j; i += d, j -= d) { if (s.charAt(i) != s.charAt(j)) { cnt++; } } } res = Math.min(res, cnt); } } return res; }
privateintdfs(int i, String s, int n, int k, int[][] change, int[][] dp) { if (k == 0) { return change[i][n - 1]; }
if (dp[i][k] != -1) { return dp[i][k]; }
intres= n; for (intj= i + 1; j < n - 2 * k; j++) { res = Math.min(res, dfs(j + 1, s, n, k - 1, change, dp) + change[i][j]); } return dp[i][k] = res; } }