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("."))







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值