题目:https://leetcode.com/problems/freedom-trail/
额。。。不解释大意了,题目我也不想写过程了有点繁琐,直接给出代码:
public int findRotateSteps(String ring, String key) {
int rlen = ring.length();
int klen = key.length();
int[][]dp = new int[klen+1][rlen+1];
int temp = 0,step = 0,diff = 0;
for(int i = 0;i<=klen;i++) {
for(int j = 1;j<=rlen;j++)
if(i==0)dp[i][j] = 0;
else dp[i][j] = Integer.MAX_VALUE;
}
for(int i = 1;i<=klen;i++) {
for(int j = 1;j<=rlen;j++) {
temp = Integer.MAX_VALUE;
if(ring.charAt(j-1)==key.charAt(i-1)) {
if(i==1)temp = Math.min(j-1,rlen+1-j);
else {
for(int k = 1;k<=rlen;k++)
if(dp[i-1][k]!=Integer.MAX_VALUE) {
diff = Math.abs(j-k);
step = Math.min(diff,rlen-diff);
temp = Math.min(temp,step+dp[i-1][k]);
}
}
}
dp[i][j] = temp;
}
}
/*
for(int i = 1;i<=klen;i++) {
for(int j = 1;j<=rlen;j++)
System.out.print(dp[i][j]+" ");
System.out.println();
}*/
int ans = dp[klen][1];
for(int i = 2;i<=rlen;i++) {
ans = ans < dp[klen][i]?ans:dp[klen][i];
}
return ans+klen;
}