首页 > 代码库 > 【leetcode】Freedom trail
【leetcode】Freedom trail
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。