首页 > 其他 > 详细

LeetCode 838. 推多米诺

时间:2020-07-12 19:51:11      阅读:59      评论:0      收藏:0      [点我收藏+]

一行中有 N 张多米诺骨牌,我们将每张多米诺骨牌垂直竖立。
在开始时,我们同时把一些多米诺骨牌向左或向右推。
每过一秒,倒向左边的多米诺骨牌会推动其左侧相邻的多米诺骨牌。
同样地,倒向右边的多米诺骨牌也会推动竖立在其右侧的相邻多米诺骨牌。
如果同时有多米诺骨牌落在一张垂直竖立的多米诺骨牌的两边,由于受力平衡, 该骨牌仍然保持不变。
就这个问题而言,我们会认为正在下降的多米诺骨牌不会对其它正在下降或已经下降的多米诺骨牌施加额外的力。
给定表示初始状态的字符串 "S" 。如果第 i 张多米诺骨牌被推向左边,则 S[i] = ‘L‘;如果第 i 张多米诺骨牌被推向右边,则 S[i] = ‘R‘;如果第 i 张多米诺骨牌没有被推动,则 S[i] = ‘.‘。
返回表示最终状态的字符串。

示例 1:
输入:".L.R...LR..L.."
输出:"LL.RR.LLRRLL.."

示例 2:
输入:"RR.L"
输出:"RR.L"
说明:第一张多米诺骨牌没有给第二张施加额外的力。
提示:

0 <= N <= 10^5
表示多米诺骨牌状态的字符串只含有 ‘L‘,‘R‘; 以及 ‘.‘;

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        if len(dominoes)<2:
            return dominoes
        last_ans = dominoes
        ans = None
        while 1:
            ans_list = []
            for i in range(len(last_ans)):
                if i==0:
                    pre = ‘.‘
                    cur = last_ans[i]
                    cur_next = last_ans[i+1]
                elif i==len(last_ans)-1:
                    pre = last_ans[i-1]
                    cur = last_ans[i]
                    cur_next = ‘.‘
                else:
                    pre = last_ans[i-1]
                    cur = last_ans[i]
                    cur_next = last_ans[i+1]
                if cur !=‘.‘:
                    ans_list.append(cur)
                else:
                    if pre == ‘R‘ and cur_next == ‘L‘:
                        ans_list.append(cur)
                    elif pre == ‘R‘:
                        ans_list.append(‘R‘)
                    elif cur_next == ‘L‘:
                        ans_list.append(‘L‘) 
                    else:
                        ans_list.append(‘.‘)
            ans =  ‘‘.join(ans_list)
            #print(ans)
            if ans == last_ans:
                break
            else:
                last_ans = ans
        return ans

LeetCode 838. 推多米诺

原文:https://www.cnblogs.com/sandy-t/p/13289333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!