力扣刷题日记-1138. 字母板上的路径

93 阅读1分钟

我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]。

在本题里,字母板为board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"],如下所示。

来源:力扣(LeetCode) 链接:leetcode.cn/problems/al… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这题有点奇怪,那四个if判断条件换个位置按道理是无关紧要的,因为如果我在a,那么,当前我向右走再向下,或者先向下再向右,都应该没有关系.但是答案把if判断换位置居然不能通过.

/**
 * @param {string} target
 * @return {string}
 */
var alphabetBoardPath = function (target) {
    let cx = 0, cy = 0, res = '';
    for (let i = 0; i < target.length; i++) {
        let n = target[i]
        let nx = Math.floor((n.charCodeAt() - 'a'.charCodeAt()) % 5)
        let ny = Math.floor((n.charCodeAt() - 'a'.charCodeAt()) / 5)

        if (cy > ny) {
            for (let k = 0; k < cy - ny; k++) {
                res += 'U'
            }
        }
        if (cx > nx) {
            for (let k = 0; k < cx - nx; k++) {
                res += 'L'
            }
        }
        if (cy < ny) {
            for (let k = 0; k < ny - cy; k++) {
                res += 'D'
            }
        }
        if (cx < nx) {
            for (let k = 0; k < nx - cx; k++) {
                res += 'R'
            }
        }

        cx = nx
        cy = ny
        res += '!'
    }
    return res
};