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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| package com.shain.dp.pathSum.bottomUpTraverse;
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public class FreedomTrail_L514 { public static void main(String[] args) { System.out.println(findRotateSteps("godding", "godding")); }
public static int findRotateSteps(String ring, String key) { int[][] dp = new int[key.length() + 1][ring.length()];
Map<Character, List<Integer>> hash = new HashMap<>(); for (int i = 0; i < ring.length(); i++) { hash.putIfAbsent(ring.charAt(i), new ArrayList<>()); hash.get(ring.charAt(i)).add(i); }
for (int i = key.length() - 1; i >= 0; i--) { for (int j = 0; j <= ring.length() - 1; j++) { List<Integer> indexes = hash.get(key.charAt(i)); int curValue = Integer.MAX_VALUE; for (Integer index : indexes) { int pos = Math.abs(j - index); int neg = ring.length() - pos; int curMin = Math.min(pos, neg); int childValue = curMin + dp[i + 1][index] + 1; curValue = Math.min(curValue, childValue); } dp[i][j] = curValue; } }
return dp[0][0]; } }
|