LeetCode 题解工作台
字母板上的路径
我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0] 。 在本题里,字母板为 board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] ,如下所示。 我们可以按下面的指令规则行动: 如果方格存在, 'U'…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
从起点 $(0, 0)$ 出发,模拟每一步的移动,将每一步的移动结果拼接到答案中。注意移动的方向遵循“左、上、右、下”的顺序。 时间复杂度 ,其中 是字符串 的长度,需要遍历字符串 中的每一个字符。忽略答案的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
我们从一块字母板上的位置 (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 <= 100target仅含有小写英文字母。
解题思路
方法一:模拟
从起点 出发,模拟每一步的移动,将每一步的移动结果拼接到答案中。注意移动的方向遵循“左、上、右、下”的顺序。
时间复杂度 ,其中 是字符串 的长度,需要遍历字符串 中的每一个字符。忽略答案的空间消耗,空间复杂度 。
class Solution:
def alphabetBoardPath(self, target: str) -> str:
i = j = 0
ans = []
for c in target:
v = ord(c) - ord("a")
x, y = v // 5, v % 5
while j > y:
j -= 1
ans.append("L")
while i > x:
i -= 1
ans.append("U")
while j < y:
j += 1
ans.append("R")
while i < x:
i += 1
ans.append("D")
ans.append("!")
return "".join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the length of the target string, as each letter's position lookup and move calculation is done in constant time. Space complexity is O(1) due to the fixed size of the board and hash table, since the hash table only stores the positions of 26 letters. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate understanding of the hash table for efficient letter position lookup.
- question_mark
Look for the ability to optimize movement calculations and reduce unnecessary steps.
- question_mark
Check if the candidate can maintain efficient space and time complexity while handling string manipulation.
常见陷阱
外企场景- error
Overcomplicating the move calculation process, leading to inefficient or incorrect paths.
- error
Forgetting to account for the exact movement required between rows and columns.
- error
Not leveraging the hash table properly, leading to repeated scans of the board.
进阶变体
外企场景- arrow_right_alt
Consider an extended board where rows and columns are dynamically added.
- arrow_right_alt
What if the board is provided as a list of strings where each row can vary in length?
- arrow_right_alt
How would this approach change if the board contains more than one key per position?