动态规划——Freedom Trail

题目:https://leetcode.com/problems/freedom-trail/

额。。。不解释大意了,题目我也不想写过程了有点繁琐,直接给出代码:

 1 public int findRotateSteps(String ring, String key) {
 2         int rlen = ring.length();
 3         int klen = key.length();
 4         int[][]dp = new int[klen+1][rlen+1];
 5         int temp = 0,step = 0,diff = 0;
 6         for(int i = 0;i<=klen;i++) {
 7             for(int j = 1;j<=rlen;j++)
 8                 if(i==0)dp[i][j] = 0;
 9                 else dp[i][j] = Integer.MAX_VALUE;
10         }
11         for(int i = 1;i<=klen;i++) {
12             for(int j = 1;j<=rlen;j++) {
13                 temp = Integer.MAX_VALUE;
14                 if(ring.charAt(j-1)==key.charAt(i-1)) {
15                     if(i==1)temp = Math.min(j-1,rlen+1-j);
16                     else {
17                         for(int k = 1;k<=rlen;k++)
18                             if(dp[i-1][k]!=Integer.MAX_VALUE) {
19                                 diff = Math.abs(j-k);
20                                 step = Math.min(diff,rlen-diff);
21                                 temp = Math.min(temp,step+dp[i-1][k]);
22                             }
23                     }
24                 }
25                 dp[i][j] = temp;
26             }
27         }
28         /*
29         for(int i = 1;i<=klen;i++) {
30             for(int j = 1;j<=rlen;j++)
31                 System.out.print(dp[i][j]+" ");
32             System.out.println();
33         }*/
34         int ans = dp[klen][1];
35         for(int i = 2;i<=rlen;i++) {
36             ans = ans < dp[klen][i]?ans:dp[klen][i];
37         }
38         return ans+klen;
39     }

 

posted @ 2018-11-11 21:34  messi2017  阅读(220)  评论(0编辑  收藏  举报