| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.FreedomTrail; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FreedomTrailDynamicProgramming : IFreedomTrail |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(m * n^2) |
| | 19 | | /// Space complexity - O(m * n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="ring"></param> |
| | 22 | | /// <param name="key"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int FindRotateSteps(string ring, string key) |
| 6 | 25 | | { |
| 12 | 26 | | int n = ring.Length, m = key.Length; |
| | 27 | |
|
| 6 | 28 | | var dp = new int[m + 1, n]; |
| | 29 | |
|
| 158 | 30 | | for (var i = 0; i <= m; i++) |
| 73 | 31 | | { |
| 1840 | 32 | | for (var j = 0; j < n; j++) |
| 847 | 33 | | { |
| 847 | 34 | | dp[i, j] = int.MaxValue; |
| 847 | 35 | | } |
| 73 | 36 | | } |
| | 37 | |
|
| 6 | 38 | | dp[0, 0] = 0; |
| | 39 | |
|
| 146 | 40 | | for (var i = 1; i <= m; i++) |
| 67 | 41 | | { |
| 1740 | 42 | | for (var j = 0; j < n; j++) |
| 803 | 43 | | { |
| 803 | 44 | | if (ring[j] != key[i - 1]) |
| 668 | 45 | | { |
| 668 | 46 | | continue; |
| | 47 | | } |
| | 48 | |
|
| 3780 | 49 | | for (var k = 0; k < n; k++) |
| 1755 | 50 | | { |
| 1755 | 51 | | if (dp[i - 1, k] == int.MaxValue) |
| 1473 | 52 | | { |
| 1473 | 53 | | continue; |
| | 54 | | } |
| | 55 | |
|
| 282 | 56 | | var steps = Math.Min((j - k + n) % n, (k - j + n) % n); |
| 282 | 57 | | dp[i, j] = Math.Min(dp[i, j], dp[i - 1, k] + steps + 1); |
| 282 | 58 | | } |
| 135 | 59 | | } |
| 67 | 60 | | } |
| | 61 | |
|
| 6 | 62 | | var minSteps = int.MaxValue; |
| | 63 | |
|
| 100 | 64 | | for (var j = 0; j < n; j++) |
| 44 | 65 | | { |
| 44 | 66 | | if (ring[j] == key[m - 1]) |
| 8 | 67 | | { |
| 8 | 68 | | minSteps = Math.Min(minSteps, dp[m, j]); |
| 8 | 69 | | } |
| 44 | 70 | | } |
| | 71 | |
|
| 6 | 72 | | return minSteps; |
| 6 | 73 | | } |
| | 74 | | } |