funcfindRotateSteps(ring string, key string)int { m, n := len(ring), len(key) memo = make([][]int, m) for i := range memo { memo[i] = make([]int, n) } charToIndex = make(map[rune][]int) // 记录盘上每一个字符的位置 for i, v := range ring { charToIndex[v] = append(charToIndex[v], i) } return dp(ring, 0, key, 0) }
funcdp(ring string, i int, key string, j int)int { // base case: 已经完成输入 if j == len(key) { return0 } if memo[i][j] != 0 { return memo[i][j] }
m := len(ring) res := math.MaxInt16
// 尝试拨动指针到当前字母 key[j] 在转盘上的每一个位置 k for _, k := range charToIndex[rune(key[j])] { delta := abs(k - i) // 计算拨动指针的次数 delta = min(delta, m - delta) // 顺时针和逆时针哪个近