1138. 字母板上的路径

我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]。
在本题里,字母板为board = [“abcde”, “fghij”, “klmno”, “pqrst”, “uvwxy”, “z”],如下所示。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/alphabet-board-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution(object):
def alphabetBoardPath(self, target):
"""
:type target: str
:rtype: str
"""
operation = list()
current_location = [0,0]
for tar in target:
row = (ord(tar) - 97) / 5
col = (ord(tar) - 97) % 5
row_moving = row - current_location[0]
col_moving = col - current_location[1]
if current_location[0] == 5 and row_moving !=0 and col_moving != 0:
operation += "U"
current_location[0] -= 1
row_moving += 1
if col_moving > 0:
operation += ["R"] * col_moving
current_location[1] += col_moving
if col_moving < 0:
operation += ["L"] * abs(col_moving)
current_location[1] += col_moving
if row_moving > 0:
operation += ["D"] * row_moving
current_location[0] += row_moving
if row_moving < 0:
operation += ["U"] * abs(row_moving)
current_location[0] += row_moving
operation += ["!"]
print(operation,row_moving,col_moving)
return "".join(operation)