public class Solution {
public int findRotateSteps(String ring, String key) {
int keyLen = key.length();
int ringLen = ring.length();
List<List<Integer>> index = new ArrayList<List<Integer>>();
for (int i = 0; i < 26; i++) {
index.add(new ArrayList<Integer>());
}
for (int i = 0; i < ringLen; i++) {
index.get(ring.charAt(i) - 'a').add(i);
}
int[] dp = new int[ringLen];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
List<Integer> start = new ArrayList<Integer>(Arrays.asList(0));
for (int i = 0; i < keyLen; i++) {
int[] nextDP = new int[ringLen];
Arrays.fill(nextDP, Integer.MAX_VALUE);
for (Integer pre : start) {// index of previous location
for (Integer cur : index.get(key.charAt(i) - 'a')) {
//int diff = cur >= pre ? cur - pre : pre - cur;
int diff = (pre + ringLen - cur) % ringLen;
diff = Math.min(diff, ringLen - diff);
nextDP[cur] = Math.min(nextDP[cur], diff + dp[pre]);
}
}
start = index.get(key.charAt(i) - 'a');
dp = nextDP;
}
int res = Integer.MAX_VALUE;
for (int temp : dp) {
res = Math.min(res, temp);
}
return res + keyLen;
}
}
/*
"godding"
"gd"
"edcba"
"abcde"
"nyngl"
"yyynnnnnnlllggg"
"iotfo"
"fioot"
*/