LeetCode-in-Java

2211. Count Collisions on a Road

Medium

There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point.

You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.

The number of collisions can be calculated as follows:

After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.

Return the total number of collisions that will happen on the road.

Example 1:

Input: directions = “RLRSLL”

Output: 5

Explanation: The collisions that will happen on the road are:

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.

Constraints:

Solution

import java.util.ArrayDeque;
import java.util.Deque;

public class Solution {
    public int countCollisions(String directions) {
        if (directions == null || directions.length() == 1) {
            return 0;
        }
        Deque<Character> stack = new ArrayDeque<>();
        char[] direction = directions.toCharArray();
        char prevc = '0';
        int collision = 0;
        for (int i = 0; i < direction.length; i++) {
            if (direction[i] == 'R') {
                stack.push(direction[i]);
            } else {
                if ((direction[i] == 'S' && prevc == 'R')) {
                    if (!stack.isEmpty()) {
                        stack.pop();
                    }
                    collision += 1;
                    direction[i] = 'S';
                    while (!stack.isEmpty()) {
                        collision++;
                        stack.pop();
                    }
                }
                if ((direction[i] == 'L' && prevc == 'R')) {
                    stack.pop();
                    collision += 2;
                    direction[i] = 'S';
                    while (!stack.isEmpty()) {
                        collision++;
                        stack.pop();
                    }
                }
                if (direction[i] == 'L' && prevc == 'S') {
                    collision++;
                    direction[i] = 'S';
                }
            }
            prevc = direction[i];
        }
        return collision;
    }
}