• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
int countCollisions(string directions) {
int l = 0;
int r = directions.length() - 1;

while (l < directions.length() && directions[l] == 'L')
++l;

while (r >= 0 && directions[r] == 'R')
--r;

return count_if(begin(directions) + l, begin(directions) + r + 1,
[](char c) { return c != 'S'; });
}
};
``````

## JAVA

``````class Solution {
public int countCollisions(String directions) {
int ans = 0;
int l = 0;
int r = directions.length() - 1;

while (l < directions.length() && directions.charAt(l) == 'L')
++l;

while (r >= 0 && directions.charAt(r) == 'R')
--r;

for (int i = l; i <= r; ++i)
if (directions.charAt(i) != 'S')
++ans;

return ans;
}
}
``````

## Python

``````class Solution:
def countCollisions(self, directions: str) -> int:
l = 0
r = len(directions) - 1

while l < len(directions) and directions[l] == 'L':
l += 1

while r >= 0 and directions[r] == 'R':
r -= 1

return sum(c != 'S' for c in directions[l:r + 1])
``````