1138. Alphabet Board Path**
https://leetcode.com/problems/alphabet-board-path/
题目描述
On an alphabet board, we start at position (0, 0)
, corresponding to character board[0][0]
.
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
, as shown in the diagram below.
We may make the following moves:
'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the characterboard[r][c]
at our current position(r, c)
to the answer.
(Here, the only positions that exist on the board are positions with letters on them.)
Return a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
Example 1:
Input: target = "leet"
Output: "DDR!UURRR!!DDD!"
Example 2:
Input: target = "code"
Output: "RR!DDRR!UUL!R!"
Constraints:
1 <= target.length <= 100
target
consists only of English lowercase letters.
C++ 实现 1
观察下图, 从 A 到 B 有两种步数最少的方法.
本题的重点其实是对于字符 z
的处理. 在下面代码中, L
和 U
必须出现在 R
和 D
的前面. 这是因为, 如果是其他字符移动到 z
, 总是可以先向左然后再向下; 而从 z
移动向其他字符, 总是可以先向上然后再向右.
class Solution {
public:
string alphabetBoardPath(string target) {
int k = 0;
char prev = '\0';
string res;
while (k < target.size()) {
if (k == 0) prev = 'a';
else prev = target[k - 1];
auto current = target[k];
auto prev_i = (prev - 'a') / 5, prev_j = (prev - 'a') % 5;
auto i = (current - 'a') / 5, j = (current - 'a') % 5;
// 注意 `L` 和 `U` 必须出现在 `R` 和 `D` 的前面.
if (j < prev_j) res += string(prev_j - j, 'L');
if (i < prev_i) res += string(prev_i - i, 'U');
if (j > prev_j) res += string(j - prev_j, 'R');
if (i > prev_i) res += string(i - prev_i, 'D');
res += '!';
++ k;
}
return res;
}
};