举例:
输入: ring = "godding", key = "gd"
输出: 4
var findRotateSteps = function(ring, key) {
const indexMap = {}
for(let i = 0; i < ring.length; i++){
const c = ring[i]
if(indexMap[c]){
indexMap[c].push(i)
}else{
indexMap[c] = [i]
}
}
const map = new Map()
function dfs(ringIndex, keyIndex){
const haha = ringIndex * 10000 + keyIndex
if(map.has(haha)){
return map.get(haha)
}
if(keyIndex === key.length){
return 0
}
const current = key[keyIndex]
let res = Infinity
for(let item of indexMap[current]){
const d1 = Math.abs(item - ringIndex)
const d2 = ring.length - d1
const currentMin = Math.min(d1, d2)
res = Math.min(res, currentMin + dfs(item, keyIndex + 1))
}
map.set(haha, res)
return res
}
return dfs(0, 0) + key.length
};