1138. Alphabet Board Path**

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 character board[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 的处理. 在下面代码中, LU 必须出现在 RD 的前面. 这是因为, 如果是其他字符移动到 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值