Alphabet Board Path LeetCode solution in Python

1
# Runtime: 68 ms (Top 16.25%) | Memory: 14 MB (Top 13.50%)
2
class Solution:
3
def alphabetBoardPath(self, target: str) -> str:
4
def shortestPath(r, c, tr, tc):
5
path = ""
6
pr = r
7
while r > tr:
8
path += "U"
9
r -= 1
10
while r < tr:
11
path += "D"
12
r += 1
13
if tr == 5 and pr != tr:
14
path = path[: len(path) - 1]
15
while c > tc:
16
path += "L"
17
c -= 1
18
while c < tc:
19
path += "R"
20
c += 1
21
if tr == 5 and pr != tr:
22
path = path + "D"
23
return path
24

25
table = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
26
r, c = 0, 0
27
ans = ""
28
for character in target:
29
t_row = None
30
for i, word in enumerate(table):
31
if character in word:
32
t_row = i
33
break
34
t_col = table[i].index(character)
35
ans += shortestPath(r, c, t_row, t_col) + "!"
36
r, c = t_row, t_col
37
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0