-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount Collisions on a Road.java
More file actions
39 lines (39 loc) · 1.26 KB
/
Count Collisions on a Road.java
File metadata and controls
39 lines (39 loc) · 1.26 KB
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
class Solution {
public int countCollisions(String directions) {
int count = 0;
Stack<Character> stk = new Stack<>();
for(int i=0;i<directions.length();i++){
char curr = directions.charAt(i);
if(stk.isEmpty() && curr == 'L'){
continue;
}else if(curr == 'R'){
stk.push(curr);
}else if(curr == 'L'){
boolean crashed = false;
while(!stk.isEmpty()){
if(stk.peek() == 'R'){
stk.pop();
count += crashed ? 1 : 2;
crashed = true;
}else if(stk.peek() == 'S'){
stk.pop();
count += crashed ? 0 : 1;//
break;
}
}
stk.push('S');
}else if(curr == 'S'){
while(!stk.isEmpty()){
if(stk.peek() == 'R'){
stk.pop();
count += 1;;
}else if(stk.peek() == 'S'){
break;
}
}
stk.push('S');
}
}
return count;
}
}