Alphabet Board Path LeetCode solution in Python
1# Runtime: 68 ms (Top 16.25%) | Memory: 14 MB (Top 13.50%)2class Solution:3def alphabetBoardPath(self, target: str) -> str:4def shortestPath(r, c, tr, tc):5path = ""6pr = r7while r > tr:8path += "U"9r -= 110while r < tr:11path += "D"12r += 113if tr == 5 and pr != tr:14path = path[: len(path) - 1]15while c > tc:16path += "L"17c -= 118while c < tc:19path += "R"20c += 121if tr == 5 and pr != tr:22path = path + "D"23return path2425table = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]26r, c = 0, 027ans = ""28for character in target:29t_row = None30for i, word in enumerate(table):31if character in word:32t_row = i33break34t_col = table[i].index(character)35ans += shortestPath(r, c, t_row, t_col) + "!"36r, c = t_row, t_col37return ans