码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Freedom trail

时间:2017-03-05 13:20:59      阅读:554      评论:0      收藏:0      [点我收藏+]

标签:for   char   str   public   color   eps   abs   string   cto   

class Solution {
public:
    int findRotateSteps(string ring, string key) {
        int M = ring.size();
        int N = key.size();
        auto f = vector<vector<int>>(M,vector<int>(N + 1,-1));
        f[0][0] = 0;
        
        for (int j = 0;j<N;j++) {
            for (int i = 0;i<M;i++) {
            if (f[i][j] == -1) continue;
            char target = key[j];
            
            for (int k = -M;k <= M;k++) {
                int index = i + k;
                if (index < 0) index += M;
                index = index % M;
                if (ring[index] == target) {
                    if (f[index][j + 1] == -1 || f[index][j + 1] > f[i][j] + 1 + fabs(k) ) {
                        f[index][j + 1] = f[i][j] + 1 + fabs(k);
                    }
                }
            }
            }
        }
        
        int ret = -1;
        for (int i = 0;i<M;i++) {
            if (f[i][N] != -1)
            if (ret == -1 || ret > f[i][N]) ret = f[i][N];
        }
        return ret;
    }
};

差5分钟,马丹

【leetcode】Freedom trail

标签:for   char   str   public   color   eps   abs   string   cto   

原文地址:http://www.cnblogs.com/soya/p/6504864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!