514. Freedom Trail #158
-
Topics: In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door. Given a string Initially, the first character of the ring is aligned at the At the stage of rotating the ring to spell the key character
Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's a breakdown of how we approach it: Problem UnderstandingWe are given two strings:
For each character in Steps for the Solution
Let's implement this solution in PHP: 514. Freedom Trail <?php
class Solution {
/**
* @param String $ring
* @param String $key
* @return Integer
*/
function findRotateSteps($ring, $key) {
$len_key = strlen($key);
$len_ring = strlen($ring);
// Create an array to store the positions of each character in the ring
$char_positions = array();
for ($index = 0; $index < $len_ring; $index++) {
$char = $ring[$index];
$char_positions[$char][] = $index;
}
// DP array to store the minimum steps required
$dp = array_fill(0, $len_key, array_fill(0, $len_ring, INF));
// Initialize the dp for the first character in key
foreach ($char_positions[$key[0]] as $j) {
$dp[0][$j] = min($j, $len_ring - $j) + 1; // +1 for pressing the button
}
// DP processing for each subsequent character in key
for ($i = 1; $i < $len_key; $i++) {
foreach ($char_positions[$key[$i]] as $j) {
foreach ($char_positions[$key[$i - 1]] as $k) {
// Calculate the minimum steps to move from position k to j
$distance = min(abs($j - $k), $len_ring - abs($j - $k));
$dp[$i][$j] = min($dp[$i][$j], $dp[$i - 1][$k] + $distance + 1);
}
}
}
// Find the minimum steps to spell the entire key
$min_steps = INF;
foreach ($char_positions[$key[$len_key - 1]] as $j) {
$min_steps = min($min_steps, $dp[$len_key - 1][$j]);
}
return $min_steps;
}
}
// Test cases
$solution = new Solution();
echo $solution->findRotateSteps("godding", "gd") . "\n"; // Output: 4
echo $solution->findRotateSteps("godding", "godding") . "\n"; // Output: 13
?> Explanation:
Time Complexity
Thus, the solution efficiently handles the problem's constraints and gives the correct minimum steps to spell the |
Beta Was this translation helpful? Give feedback.
Here's a breakdown of how we approach it:
Problem Understanding
We are given two strings:
ring
: the circular ring of characters.key
: the word we need to spell by rotating the ring.For each character in
key
, we rotate thering
to align the character at the top (index0
), and this rotation can happen either clockwise or anticlockwise. The goal is to find the minimum number of rotations (steps) required to spell all the characters ofkey
.Steps for the Solution
Character Positions:
ring
. This allows us to efficiently look up all positions where a given character appears.Dynamic Programming Table:
dp[i][j]
represent the m…