514. Freedom Trail
- Total Accepted: 1193
- Total Submissions: 3901
- Difficulty: Hard
- Contributors: Rabby250
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 in order to open the door.
Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.
Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button.At the stage of rotating the ring to spell the key character key[i]:
- You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i].
- If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.
Note:
- Length of both ring and key will be in range 1 to 100.
- There are only lowercase letters in both strings and might be some duplcate characters in both strings.
- It's guaranteed that string key could always be spelled by rotating the string ring.
思路:
在计算顺时针和逆时针转动时,分别采用(当前位置+环的长度-关键字位置)%环的长度、(
关键字位置+环的长度-当前位置)%环的长度,再取其中较小的一个加上之前的步数,并把它记录到一个二维数组record。数组tmp1记录关键字位置,tmp2记录当前位置。对每个关键字,记录环中所在的所有位置,然后一一比较,取其中最小的一个。
代码:
class Solution {
public:
int findRotateSteps(string ring, string key) {
int size = ring.size();
int ksize = key.size();
int record[110][110];
int steps;
int sum = 100000000;
for(int i = 0; i < 102; i ++){
for(int j = 0; j < 102; j ++){
if(i == 0) record[i][j] = 0;
else record[i][j] = 10000000;
}
}
vector
tmp1;
vector
tmp2;
tmp2.push_back(0);
for(int i = 1; i <= ksize; i ++){
for(int j = 0; j < size; j ++){
if(key[i-1] == ring[j]) tmp1.push_back(j);
}
for(int k = 0; k < tmp1.size(); k ++){
for(int l = 0; l < tmp2.size(); l ++){
steps = min((tmp2[l] + size - tmp1[k]) % size, (tmp1[k] + size - tmp2[l]) % size) + record[i-1][tmp2[l]];
record[i][tmp1[k]] = min(record[i][tmp1[k]], steps);
sum = (i != ksize? sum : min(sum, record[i][tmp1[k]]));
}
}
tmp2 = tmp1;
tmp1.clear();
}
return sum + ksize;
}
};