838. Push Dominoes

There are N dominoes in a line, and we place each domino vertically upright.

In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

After each second, each domino that is falling to the left pushes the adjacent domino on the left.

Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.

When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.

For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.

Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.

Return a string representing the final state. 

Example 1:

Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."

Example 2:

Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.

Note:

  1. 0 <= N <= 10^5
  2. String dominoes contains only 'L', 'R' and '.'

每个LR中间的interval求一遍,然后单独处理一下2边缘

class Solution(object):
    def pushDominoes(self, s):
        """
        :type dominoes: str
        :rtype: str
        """
        if not s: return s
        s = [t for t in s]
        q = []
        for i in range(len(s)):
            if s[i]=='L': q.append((i,'L'))
            elif s[i]=='R': q.append((i,'R'))
        if not q: return ''.join(s)
        
        idxS = 0
        idxE = len(q)-1
        if q[0][1]=='L':
            for i in range(q[0][0]): s[i]='L'
        if q[-1][1]=='R':
            for i in range(q[-1][0], len(s)): s[i]='R'
        
        for i in range(idxS, idxE):
            if q[i][1]==q[i+1][1]:
                for j in range(q[i][0], q[i+1][0]+1):
                    s[j] = q[i][1]
            elif q[i][1]=='R' and q[i+1][1]=='L':
                t1, t2 = q[i][0], q[i+1][0]
                while t1<t2:
                    s[t1]=q[i][1]
                    s[t2]=q[i+1][1]
                    t1, t2 = t1+1, t2-1
                
        return ''.join(s)
    
s=Solution()
print(s.pushDominoes(".L.R...LR..L.."))
print(s.pushDominoes("RR.L"))
print(s.pushDominoes("."))







猜你喜欢

转载自blog.csdn.net/zjucor/article/details/80380899
今日推荐