我们从一块字母板上的位置 (0, 0)
出发,该坐标对应的字符为 board[0][0]
。
在本题里,字母板为board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
.
我们可以按下面的指令规则行动:
- 如果方格存在,
'U'
意味着将我们的位置上移一行; - 如果方格存在,
'D'
意味着将我们的位置下移一行; - 如果方格存在,
'L'
意味着将我们的位置左移一列; - 如果方格存在,
'R'
意味着将我们的位置右移一列; '!'
会把在我们当前位置(r, c)
的字符board[r][c]
添加到答案中。
返回指令序列,用最小的行动次数让答案和目标 target
相同。你可以返回任何达成目标的路径。
示例 1:
输入:target = "leet"
输出:"DDR!UURRR!!DDD!"
示例 2:
输入:target = "code"
输出:"RR!DDRR!UUL!R!"
提示:
1 <= target.length <= 100
target
仅含有小写英文字母。
思路:
先开个哈希表并遍历board,记录每个字母的坐标,
然后对于target里的每个字符,从当前坐标(起始为(0, 0))走到目标坐标(读哈希表得到),
唯一的特殊情况是字母“z”,因为它只能从上一个字母“u”向下走到。
class Solution(object):
def alphabetBoardPath(self, target):
"""
:type target: str
:rtype: str
"""
board = ["abcde",
"fghij",
"klmno",
"pqrst",
"uvwxy",
"z"]
dic = dict()
for i in range(len(board)):
for j in range(len(board[0])):
dic[board[i][j]] = [i, j]
if i == 5:
break
x0, y0 = 0,0
res = ""
for char in target:
tmp = ""
des = dic[char]
x1, y1 = des[0], des[1]
if x0 == x1 and y0 == y1:
res += "!"
continue
if x0 < x1:
tmp += "D" * (x1 - x0)
elif x0 > x1:
tmp += "U" * (x0 - x1)
if x1 == 5 and tmp and tmp[-1] == "D": #处理特殊情况
tmp = tmp[:-1]
if y0 < y1:
tmp += "R" * (y1 - y0)
elif y1 < y0:
tmp += "L" * (y0 - y1)
x0 = x1
y0 = y1
if x1 == 5:#处理特殊情况
tmp += "D"
tmp += "!"
res += tmp
return res