2211. Count Collisions on a Road Medium

@problem@discussion
#String#Stack



1/**
2 * [2211] Count Collisions on a Road
3 *
4 * 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.
5 * You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the i^th car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.
6 * The number of collisions can be calculated as follows:
7 * 
8 * 	When two cars moving in opposite directions collide with each other, the number of collisions increases by 2.
9 * 	When a moving car collides with a stationary car, the number of collisions increases by 1.
10 * 
11 * 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.
12 * Return the total number of collisions that will happen on the road.
13 *  
14 * Example 1:
15 * 
16 * Input: directions = "RLRSLL"
17 * Output: 5
18 * Explanation:
19 * The collisions that will happen on the road are:
20 * - Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.
21 * - Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.
22 * - Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.
23 * - 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.
24 * Thus, the total number of collisions that will happen on the road is 5. 
25 * 
26 * Example 2:
27 * 
28 * Input: directions = "LLRR"
29 * Output: 0
30 * Explanation:
31 * No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.
32 *  
33 * Constraints:
34 * 
35 * 	1 <= directions.length <= 10^5
36 * 	directions[i] is either 'L', 'R', or 'S'.
37 * 
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/count-collisions-on-a-road/
42// discuss: https://leetcode.com/problems/count-collisions-on-a-road/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47    pub fn count_collisions(directions: String) -> i32 {
48        0
49    }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_2211() {
60    }
61}
62


Back
© 2025 bowen.ge All Rights Reserved.