java 514. Freedom Trail.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 514. Freedom Trail.java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int findRotateSteps(String ring, String key) {
        int keyLen = key.length();
        int ringLen = ring.length();
        List<List<Integer>> index = new ArrayList<List<Integer>>();
        for (int i = 0; i < 26; i++) {
            index.add(new ArrayList<Integer>());
        }
        for (int i = 0; i < ringLen; i++) {
            index.get(ring.charAt(i) - 'a').add(i);
        }
        int[] dp = new int[ringLen];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        List<Integer> start = new ArrayList<Integer>(Arrays.asList(0));
        for (int i = 0; i < keyLen; i++) {
            int[] nextDP = new int[ringLen];
            Arrays.fill(nextDP, Integer.MAX_VALUE);
            for (Integer pre : start) {// index of previous location
                for (Integer cur : index.get(key.charAt(i) - 'a')) {
                    //int diff = cur >= pre ? cur - pre : pre - cur;
                    int diff = (pre + ringLen - cur) % ringLen;
                    diff = Math.min(diff, ringLen - diff);
                    nextDP[cur] = Math.min(nextDP[cur], diff + dp[pre]);
                }
            }
            start = index.get(key.charAt(i) - 'a');
            dp = nextDP;
        }
        
        int res = Integer.MAX_VALUE;
        for (int temp : dp) {
            res = Math.min(res, temp);
        }
        return res + keyLen;
    }
}

/*
"godding"
"gd"
"edcba"
"abcde"
"nyngl"
"yyynnnnnnlllggg"
"iotfo"
"fioot"
*/

以上是关于java 514. Freedom Trail.java的主要内容,如果未能解决你的问题,请参考以下文章

java 514. Freedom Trail.java

java 514. Freedom Trail.java

java 514. Freedom Trail.java

java 514. Freedom Trail.java

514 Freedom Trail 自由之路

514. Freedom Trail