1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| class Solution { public int minimumChanges(String s, int k) { int n = s.length();
int[][] change = new int[n][n]; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { change[i][j] = calc(s.substring(i, j + 1)); } }
int[][] dp = new int[n][k]; for (int i = 0; i < n; i++) { Arrays.fill(dp[i], -1); } return dfs(0, s, n, k - 1, change, dp); }
private int calc(String s) { int n = s.length(), res = n; for (int d = 1; d < n; d++) { if (n % d == 0) { int cnt = 0; for (int k = 0; k < d; k++) { for (int i = 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; }
private int dfs(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]; }
int res = n; for (int j = 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; } }
|