LeetCode 题解工作台
执行所有后缀指令
现有一个 n x n 大小的网格,左上角单元格坐标 (0, 0) ,右下角单元格坐标 (n - 1, n - 1) 。给你整数 n 和一个整数数组 startPos ,其中 startPos = [start row , start col ] 表示机器人最开始在坐标为 (start row , s…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · string·结合·模拟
答案摘要
class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路
题目描述
现有一个 n x n 大小的网格,左上角单元格坐标 (0, 0) ,右下角单元格坐标 (n - 1, n - 1) 。给你整数 n 和一个整数数组 startPos ,其中 startPos = [startrow, startcol] 表示机器人最开始在坐标为 (startrow, startcol) 的单元格上。
另给你一个长度为 m 、下标从 0 开始的字符串 s ,其中 s[i] 是对机器人的第 i 条指令:'L'(向左移动),'R'(向右移动),'U'(向上移动)和 'D'(向下移动)。
机器人可以从 s 中的任一第 i 条指令开始执行。它将会逐条执行指令直到 s 的末尾,但在满足下述条件之一时,机器人将会停止:
- 下一条指令将会导致机器人移动到网格外。
- 没有指令可以执行。
返回一个长度为 m 的数组 answer ,其中 answer[i] 是机器人从第 i 条指令 开始 ,可以执行的 指令数目 。
示例 1:

输入:n = 3, startPos = [0,1], s = "RRDDLU" 输出:[1,5,4,3,1,0] 解释:机器人从 startPos 出发,并从第 i 条指令开始执行: - 0: "RRDDLU" 在移动到网格外之前,只能执行一条 "R" 指令。 - 1: "RDDLU" 可以执行全部五条指令,机器人仍在网格内,最终到达 (0, 0) 。 - 2: "DDLU" 可以执行全部四条指令,机器人仍在网格内,最终到达 (0, 0) 。 - 3: "DLU" 可以执行全部三条指令,机器人仍在网格内,最终到达 (0, 0) 。 - 4: "LU" 在移动到网格外之前,只能执行一条 "L" 指令。 - 5: "U" 如果向上移动,将会移动到网格外。
示例 2:

输入:n = 2, startPos = [1,1], s = "LURD" 输出:[4,1,0,0] 解释: - 0: "LURD" - 1: "URD" - 2: "RD" - 3: "D"
示例 3:

输入:n = 1, startPos = [0,0], s = "LRUD" 输出:[0,0,0,0] 解释:无论机器人从哪条指令开始执行,都会移动到网格外。
提示:
m == s.length1 <= n, m <= 500startPos.length == 20 <= startrow, startcol < ns由'L'、'R'、'U'和'D'组成
解题思路
方法一
class Solution:
def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
ans = []
m = len(s)
mp = {"L": [0, -1], "R": [0, 1], "U": [-1, 0], "D": [1, 0]}
for i in range(m):
x, y = startPos
t = 0
for j in range(i, m):
a, b = mp[s[j]]
if 0 <= x + a < n and 0 <= y + b < n:
x, y, t = x + a, y + b, t + 1
else:
break
ans.append(t)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m*n) because each of the m suffixes may simulate up to n moves in the worst case. Space complexity is O(m) for storing results. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if you notice simulation is feasible given small constraints.
- question_mark
Looks for handling edge cases when the robot is at a grid boundary.
- question_mark
Evaluates if the approach efficiently stops at invalid moves.
常见陷阱
外企场景- error
Not stopping immediately when a move goes off the grid, leading to incorrect counts.
- error
Incorrectly updating coordinates causing off-by-one errors.
- error
Confusing the starting index with the overall string length when iterating suffixes.
进阶变体
外企场景- arrow_right_alt
Simulate instructions on a non-square grid or rectangular grid.
- arrow_right_alt
Count moves until a specific target cell is reached instead of leaving the grid.
- arrow_right_alt
Allow diagonal moves and adapt the delta updates accordingly.