https://leetcode.com/problems/freedom-trail/#/description
给一个环和一个key,判断环经多少步可以得到key,
Input: ring = "godding", key = "gd" Output: 4 Explanation:
For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
Also, we need 1 more step for spelling.
So the final output is 4.
public class Solution {
public int findRotateSteps(String ring, String key) {
int n = ring.length(), m = key.length();
int[][] dp = new int[m + 1][n];
int[][] clock = preproc(ring, 1), anti = preproc(ring, -1);
for (int i = m - 1; i >= 0; --i) {
int idx = key.charAt(i) - 'a';
for (int j = 0; j < n; ++j) { // fill dp[i][j]
int p = clock[j][idx];
int q = anti[j][idx];
// 顺时针从i ~ p走过的路径是i与p之间包含12点钟位置的那一段!!实际转一下圆环就知道
dp[i][j] = Math.min(dp[i + 1][p] + (j + n - p) % n, dp[i + 1][q] + (q + n - j) % n);
}
}
return dp[0][0] + m;
}
// ans[i]表示以i位置为视角,正/反向离char[i]最近的各字母index是多少
int[][] preproc(String r, int inc) {
int n = r.length();
int[][] ans = new int[n][26];
int[] map = new int[26];
// 要遍历两个长度才能保证前面的index知道后面的值是什么
for (int i = 0, j = 0; j < n * 2 - 1; ++j) {
map[r.charAt(i) - 'a'] = i;
System.arraycopy(map, 0, ans[i], 0, 26);
i = (i + inc + n) % n;
}
return ans;
}
}