#2211

Count Collisions on a Road

specialist · 765 · lc medium +31 · verified · 58.1% accepted · 1,101 likes · top 54%

Description

There are n cars on an infinitely long road, numbered 0 to n - 1 from left to right, each at a unique position.

You are given a 0-indexed string directions of length n. directions[i] is 'L' (moving left), 'R' (moving right), or 'S' (stationary). All moving cars travel at the same speed.

Collisions occur as follows:

- Two cars colliding head-on contribute 2 to the collision count.

- A moving car hitting a stationary car contributes 1.

After a collision, cars stop permanently at the collision point.

Return the total number of collisions that will occur.

Example 1:

Input: directions = "RLRSLL"
Output: 5
Explanation:
The collisions that will happen on the road are:
- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.
- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.
- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.
- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.
Thus, the total number of collisions that will happen on the road is 5.

Example 2:

Input: directions = "LLRR"
Output: 0
Explanation:
No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.

Code

1
2
3