推倒多米诺骨牌

问题描述
有 N 张多米诺骨牌,将每张多米诺骨牌垂直竖立。在开始时,同时把一些多米诺骨牌向左或向右推(初始状态)。以字符串的形式给定多米诺骨牌的初始状态,在给定字符串中:
. 代表该位置的多米诺骨牌保持静止。
L 代表将该位置的多米诺骨牌向左倒。
R 代表将该位置的多米诺骨牌向右倒。
每过一秒,倒向左边的多米诺骨牌会推动其左侧相邻的多米诺骨牌。同样地,倒向右边的多米诺骨牌也会推动竖立在其右侧的相邻多米诺骨牌。如果同时有多米诺骨牌落在一张垂直竖立的多米诺骨牌的两边,由于受力平衡, 该骨牌仍然保持不变。基于以上考虑,输出对给定初始状态的多米诺骨牌稳定后的最终状态。

测试样例

输入: '..R.....L..R.'
输出: '..RRR.LLL..RR'

内容首发于微信公众号IT信息教室,如果您想学习更多AI相关的技能,欢迎搜索关注或微信扫描下方二维码关注~~

在这里插入图片描述

参考代码

# O(n) time, O(n) space, where n is the number of dominoes.
class Solution():
    def pushDominoes(self, dominoes):
        N = len(dominoes)
        force = [0] * N
        
        # Populate force from left to right.
        currentForce = 0
        for idx in range(N):
            if dominoes[idx] == 'R':
                currentForce = N
            elif dominoes[idx] == 'L':
                currentForce = 0
            else:
                currentForce = max(currentForce - 1, 0)
            force[idx] += currentForce
            
        # Populate force from right to left.
        currentForce = 0
        for idx in reversed(range(N)):
            if dominoes[idx] == 'L':
                currentForce = -N
            elif dominoes[idx] == 'R':
                currentForce = 0
            else:
                currentForce = min(currentForce + 1, 0)
            force[idx] += currentForce
        return force
    
    # Convert list to string.
    def getFinalState(self, dominoes):
        finalState = self.pushDominoes(dominoes)
        result = ''
        for currentForce in finalState:
            if currentForce == 0:
                result += '.'
            elif currentForce > 0:
                result += 'R'
            elif currentForce < 0:
                result += 'L'
        return result
          
# Test Program
dominoes = '..R.....L..R.'
print(Solution().getFinalState(dominoes))
#..RRR.LLL..RR
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值