[leetcode] 1138. Alphabet Board Path

Description

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.

分析

题目的意思是:给定一个字符的board,和一个target字符串,求在board找到target的路径。这道题我看了别人的解法,首先从(0,0)出发到达每个字符的路径是可以通过坐标计算出来的,这样的话,我们把每个字符在board上的坐标算出来,然后求一下需要向左右上下走的步骤,就可以得出路径了。如果能想到这一点,就比较容易的写出来了。

代码

class Solution:
    def alphabetBoardPath(self, target: str) -> str:
        n=5
        cx,cy=0,0
        res=''
        offset=ord('a')
        for ch in target:
            row=(ord(ch)-offset)//n
            col=(ord(ch)-offset)%n
            if(cy>col):
                res+='L'*(cy-col)
            if(cx>row):
                res+='U'*(cx-row)
            if(cy<col):
                res+='R'*(col-cy)
            if(cx<row):
                res+='D'*(row-cx)
            res+='!'
            cx,cy=row,col
        return res

参考文献

[LeetCode] Python | O(N) | without BFS | Faster than 90% | Less space than 100%

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值