Skip to content

Commit 8642229

Browse files
Create 0514-freedom-trail.java
1 parent 392f504 commit 8642229

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: java/0514-freedom-trail.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
Map<String, Integer> cache = new HashMap<>();
3+
4+
public int findRotateSteps(String ring, String key) {
5+
return helper(ring, key, 0, 0);
6+
}
7+
8+
private int helper(String ring, String key, int r, int k) {
9+
if (k == key.length())
10+
return 0;
11+
String keyCache = r + "," + k;
12+
if (cache.containsKey(keyCache))
13+
return cache.get(keyCache);
14+
15+
int res = Integer.MAX_VALUE;
16+
for (int i = 0; i < ring.length(); i++) {
17+
if (ring.charAt(i) == key.charAt(k)) {
18+
int minDist = Math.min(Math.abs(r - i), ring.length() - Math.abs(r - i));
19+
int steps = minDist + 1 + helper(ring, key, i, k + 1);
20+
res = Math.min(res, steps);
21+
}
22+
}
23+
24+
cache.put(keyCache, res);
25+
return res;
26+
}
27+
}

0 commit comments

Comments
 (0)