[leetcode] 838. Push Dominoes

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.
[leetcode] 838. Push Dominoes_第1张图片
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;j0) 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

你可能感兴趣的:(leetcode,C++,leetcode题解)