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

<p>You are given a <strong>0-indexed</strong> string <code>directions</code> of length <code>n</code>. <code>directions[i]</code> can be either <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, or <code>&#39;S&#39;</code> denoting whether the <code>i<sup>th</sup></code> car is moving towards the <strong>left</strong>, towards the <strong>right</strong>, or <strong>staying</strong> at its current point respectively. Each moving car has the <strong>same speed</strong>.</p>

<p>The number of collisions can be calculated as follows:</p>

<ul>
	<li>When two cars moving in <strong>opposite</strong> directions collide with each other, the number of collisions increases by <code>2</code>.</li>
	<li>When a moving car collides with a stationary car, the number of collisions increases by <code>1</code>.</li>
</ul>

<p>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.</p>

<p>Return <em>the <strong>total number of collisions</strong> that will happen on the road</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> directions = &quot;RLRSLL&quot;
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The collisions that will happen on the road are:
- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.
- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.
- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.
- 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.
Thus, the total number of collisions that will happen on the road is 5. 
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> directions = &quot;LLRR&quot;
<strong>Output:</strong> 0
<strong>Explanation:</strong>
No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= directions.length &lt;= 10<sup>5</sup></code></li>
	<li><code>directions[i]</code> is either <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, or <code>&#39;S&#39;</code>.</li>
</ul>

# 左侧'L'肯定往左开走不撞；右侧'R'肯定往右开走不撞。均剔除：s.lstrip('L').rstrip('R')
# 剩余的均会碰撞，不论'L'或'R'，都算一次。'SL'只会算'L'一次；'RS'只会算'R'一次，因此'S'均不会计入
# 剔除'S'个数directions.count('S')之后，就是题意所需结果。
# eg： RRS -> 2  第二个R撞上S之后静止变成S，第一个R会撞上，也变成S静止，所以两次，由此可得LR都会贡献一次，S不贡献

#Time O(n)  s.lstrip('L') 和 s.rstrip('R') 的操作需要遍历字符串的一部分，最坏情况下需要遍历整个字符串
#Space O(n) 创建新的字符串
class Solution:
    def countCollisions(self, s: str) -> int:
        s = s.lstrip('L')  # 前缀向左的车不会发生碰撞
        s = s.rstrip('R')  # 后缀向右的车不会发生碰撞
        return len(s) - s.count('S')  # 剩下的非停止的车必然会碰撞 #光计算LR就行; 这和LR相撞+2, LS/RS相撞+1是一个道理，都是只看LR的个数
    
#优化版本，不创建新的string
#Time O(n)  
#Space O(1)
class Solution:
    def countCollisions(self, s: str) -> int:
        left = 0
        right = len(s) - 1
        
        # 跳过前面的'L'和后面的'R'
        # 包含自身，因为要跳过所有的 ex："LLRR" -> return 0 
        while(left <= right and s[left] == 'L'): left += 1
        while(left <= right and s[right] == 'R'): right -= 1
        
        # 跳过所有左边L右边R之后
        count = 0
        for i in range(left, right + 1):#right = len(s) - 1 所以要把1加回去
            if(s[i] != 'S'):    #光计算LR就行; 这和LR相撞+2, LS/RS相撞+1是一个道理，都是只看LR的个数
                count += 1   
        
        return count
    
    
#Time O(n)  while 循环中的每个元素最多被压入和弹出 stack 一次，因此 while 循环的总操作次数是 O(n)
#Space O(n) stack
class Solution:
    def countCollisions(self, directions: str) -> int:
        stack = []
        count = 0
        
        #3种相撞case: "RS" "RL" "SL"
        #关键在于处理左边已经在stack里的R (即"RS")
        #所以要把当前相撞的处理成S("RL" "SL"), 然后再处理"RS"
        for d in directions:
            if(stack): #stack 不为空才能比较stack[-1]
                #"RL"
                if(stack[-1] == "R" and d == "L"): 
                    count += 2
                    stack.pop() #为了之后处理更左边的"R", 要把当前的"R"pop了，不要挡着
                    d = "S"     #"RL"相撞，就静止了, 为了之后处理更左边的"R"
                    
                #"SL"    
                elif(stack[-1] == "S" and d == "L"):    
                    count += 1
                    d = "S"   ##"RL"相撞，就静止了, 为了之后处理更左边的"R"
                 
                #"RS"
                #关键在于处理左边已经在stack里的R (即"RS"), 所以要把当前相撞的处理成S("RL" "SL"), 然后再处理"RS"  
                while(stack and stack[-1] == "R" and d == "S"): #d == "R"时这个能跳过
                    count += 1
                    stack.pop()
                    
            stack.append(d)

        return count
304