[leetcode] 838. Push Dominoes

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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.
domino
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 ‘.’

分析

题目的意思是:给你一排多米诺骨牌,每张牌的状态已经知道,求最终的状态。

  • 不管多米诺骨牌是否被退,最终的状态跟其两边的状态有关,并且与L和R中最短的状态有关。只是方向的问题。
'R......R' => 'RRRRRRRR' 所有的多米诺骨牌都会向右
'R......L' => 'RRRRLLLL' or 'RRRR.LLLL' 一半的多米诺骨牌向右,一半的多米诺骨牌向左或者,中间的骨牌不变,左半部分向右,右半部分向左。
'L......R' => 'L......R'  状态保持不变
'L......L' => 'LLLLLLLL'  所有的多米诺骨牌向左
  • 在写代码的时候首先跟输入左边加上一个“L”,跟右边加上一个“R”。这也是为了计算中间点的方便。

代码

class Solution {
public:
    string pushDominoes(string dominoes) {
        dominoes='L'+dominoes+'R';
        string res="";
        int i=0;
        for(int j=1;j<dominoes.length();j++){
            if(dominoes[j]=='.'){
                continue;
            }
            int middle=j-i-1;
            if(i>0) res+=dominoes[i];
            if(dominoes[i]==dominoes[j]){
                res+=string(middle,dominoes[i]);
            }else if(dominoes[i]=='L'&&dominoes[j]=='R'){
                res+=string(middle,'.');
            }else{
                res+=string(middle/2,'R')+string(middle%2,'.')+string(middle/2,'L');
            }
            i=j;
        }
        return res;
    }
};

参考文献

838. Push Dominoes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值