问题描述
有 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