算法刷题打卡第88天:字母板上的路径

字母板上的路径

难度:中等

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

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

请添加图片描述
我们可以按下面的指令规则行动:

  • 如果方格存在,'U' 意味着将我们的位置上移一行;
  • 如果方格存在,'D' 意味着将我们的位置下移一行;
  • 如果方格存在,'L' 意味着将我们的位置左移一列;
  • 如果方格存在,'R' 意味着将我们的位置右移一列;
  • '!' 会把在我们当前位置 (r, c) 的字符 board[r][c] 添加到答案中。
    (注意,字母板上只存在有字母的位置。)

返回指令序列,用最小的行动次数让答案和目标 target 相同。你可以返回任何达成目标的路径。

示例 1:

输入:target = "leet"
输出:"DDR!UURRR!!DDD!"

示例 2:

输入:target = "code"
输出:"RR!DDRR!UUL!R!"

哈希表

思路:

  • 根据字符输入,可以计算出对应的位置
  • 根据位置左右和上下移动即可
  • 需注意,移动到z只能先左右再上下,从z移动出去只能先上下再左右

复杂度分析:

  • 时间复杂度: O ( n ) O(n) O(n) n n n t a r g e t target target 长度
  • 空间复杂度: O ( c ) O(c) O(c) c c c 26 26 26
class Solution:
    def alphabetBoardPath(self, target: str) -> str:
        word_dicts = dict()
        board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
        for x, i in enumerate(board):
            for y, j in enumerate(i):
                word_dicts[j] = [x, y]
        now_position = [0, 0]
        res = ""
        
        def lr_move(target_position, now_position, res):
            if target_position[1] - now_position[1] >= 0:
                res += 'R' * abs(target_position[1] - now_position[1])
            else:
                res += 'L' * abs(target_position[1] - now_position[1])
            return res
        def ud_move(target_position, now_position, res):
            if target_position[0] - now_position[0] >= 0:
                res += 'D' * abs(target_position[0] - now_position[0])
            else:
                res += 'U' * abs(target_position[0] - now_position[0])
            return res
            
        for i in target:
            target_position = word_dicts[i]
            if i != 'z':
                res = ud_move(target_position, now_position, res)
                res = lr_move(target_position, now_position, res)
            else:              
                res = lr_move(target_position, now_position, res)
                res = ud_move(target_position, now_position, res)
            res += "!"
            now_position = target_position
        return res

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/alphabet-board-path

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏秃然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值