/
CountCollisionsOnRoad.java
47 lines (40 loc) · 1.58 KB
/
CountCollisionsOnRoad.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://leetcode.com/problems/count-collisions-on-a-road
class Solution {
public int countCollisions(String directions) {
int r = 0, l = 0, s = 0, count = 0;
int ri = -1, si = -1, li = -1, i = 0;
for (char c: directions.toCharArray()) {
// If the car is moving towards right, we count it
if (c == 'R') {
r++;
// Any previous stationary cars or cars moving left are safe
s = 0;
l = 0;
ri = i;
} else if (c == 'S') {
// All the cars that were previously travelling right will collide with this car
count += r;
r = 0;
s++;
si = i;
} else {
// Now we check for any collision
// If it will collide with S first
if (si > ri) {
count++;
} else if (ri >= 0) {
// Collision can only take place if there was indeed any car travelling R before
count += r > 0 ? 2 : 0;
// This position now becomes stationary
// But any cars that were behind the colliding with R which were travelling in R will also collide
count += r > 0 ? r - 1 : 0;
r = 0;
si = i;
}
li = i;
}
i++;
}
return count;
}
}