LeetCode 题解工作台
统计道路上的碰撞次数
在一条无限长的公路上有 n 辆汽车正在行驶。汽车按从左到右的顺序按从 0 到 n - 1 编号,每辆车都在一个 独特的 位置。 给你一个下标从 0 开始的字符串 directions ,长度为 n 。 directions[i] 可以是 'L' 、 'R' 或 'S' 分别表示第 i 辆车是向 左 …
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
根据题意,当两辆移动方向相反的车相撞时,碰撞次数加 ,即两辆车被撞停,答案加 ;当一辆移动的车和一辆静止的车相撞时,碰撞次数加 ,即一辆车被撞停,答案加 。 而显然前缀的 和后缀的 是不会发生碰撞的,所以我们只需要统计中间不等于 的字符个数即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
在一条无限长的公路上有 n 辆汽车正在行驶。汽车按从左到右的顺序按从 0 到 n - 1 编号,每辆车都在一个 独特的 位置。
给你一个下标从 0 开始的字符串 directions ,长度为 n 。directions[i] 可以是 'L'、'R' 或 'S' 分别表示第 i 辆车是向 左 、向 右 或者 停留 在当前位置。每辆车移动时 速度相同 。
碰撞次数可以按下述方式计算:
- 当两辆移动方向 相反 的车相撞时,碰撞次数加
2。 - 当一辆移动的车和一辆静止的车相撞时,碰撞次数加
1。
碰撞发生后,涉及的车辆将无法继续移动并停留在碰撞位置。除此之外,汽车不能改变它们的状态或移动方向。
返回在这条道路上发生的 碰撞总次数 。
示例 1:
输入:directions = "RLRSLL" 输出:5 解释: 将会在道路上发生的碰撞列出如下: - 车 0 和车 1 会互相碰撞。由于它们按相反方向移动,碰撞数量变为 0 + 2 = 2 。 - 车 2 和车 3 会互相碰撞。由于 3 是静止的,碰撞数量变为 2 + 1 = 3 。 - 车 3 和车 4 会互相碰撞。由于 3 是静止的,碰撞数量变为 3 + 1 = 4 。 - 车 4 和车 5 会互相碰撞。在车 4 和车 3 碰撞之后,车 4 会待在碰撞位置,接着和车 5 碰撞。碰撞数量变为 4 + 1 = 5 。 因此,将会在道路上发生的碰撞总次数是 5 。
示例 2:
输入:directions = "LLRR" 输出:0 解释: 不存在会发生碰撞的车辆。因此,将会在道路上发生的碰撞总次数是 0 。
提示:
1 <= directions.length <= 105directions[i]的值为'L'、'R'或'S'
解题思路
方法一:脑筋急转弯
根据题意,当两辆移动方向相反的车相撞时,碰撞次数加 ,即两辆车被撞停,答案加 ;当一辆移动的车和一辆静止的车相撞时,碰撞次数加 ,即一辆车被撞停,答案加 。
而显然前缀的 和后缀的 是不会发生碰撞的,所以我们只需要统计中间不等于 的字符个数即可。
时间复杂度 ,空间复杂度 或 。其中 是字符串 的长度。
class Solution:
def countCollisions(self, directions: str) -> int:
s = directions.lstrip("L").rstrip("R")
return len(s) - s.count("S")
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests understanding of stack-based state management in simulating real-world interactions.
- question_mark
Evaluates the candidate's ability to manage multiple car states (moving left, right, stationary).
- question_mark
Assesses the candidate's approach to handling edge cases, such as all cars moving in the same direction or all cars stationary.
常见陷阱
外企场景- error
Misunderstanding when collisions happen—confusing collisions between stationary cars and moving cars.
- error
Overcomplicating the simulation without efficiently managing the cars' states with a stack.
- error
Not accounting for edge cases like cars moving in the same direction or all cars being stationary.
进阶变体
外企场景- arrow_right_alt
Consider a scenario where no cars are moving; how does this affect the collision count?
- arrow_right_alt
What happens when all cars move in the same direction? How would you adjust the algorithm?
- arrow_right_alt
Extend the problem to track additional states, such as car speeds or varying collision impacts.