Leetcode 1238 Solution

This article provides solution to leetcode question 1238 (alphabet-board-path)

https://leetcode.com/problems/alphabet-board-path

Solution

class Solution:
    def alphabetBoardPath(self, target: str) -> str:
        board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]

        char_pos = {}
        for i, s in enumerate(board):
            for j, ch in enumerate(s):
                char_pos[ch] = (i, j)


        curr_ch = 'a'
        ans = ""
        for ch in target:
            src_i, src_j = char_pos[curr_ch]
            dst_i, dst_j = char_pos[ch]

            if ch != "z":
                if src_i > dst_i:
                    ans += "U" * (src_i - dst_i)
                elif src_i < dst_i:
                    ans += "D" * (dst_i - src_i)

                if src_j > dst_j:
                    ans += "L" * (src_j - dst_j)
                elif src_j < dst_j:
                    ans += "R" * (dst_j - src_j)
            else:
                if src_j > dst_j:
                    ans += "L" * (src_j - dst_j)
                elif src_j < dst_j:
                    ans += "R" * (dst_j - src_j)

                if src_i > dst_i:
                    ans += "U" * (src_i - dst_i)
                elif src_i < dst_i:
                    ans += "D" * (dst_i - src_i)

            ans += "!"

            curr_ch = ch

        return ans