[leetcode] 838. Push Dominoes

网友投稿 254 2022-08-26

[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.

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:

0 <= N <= 10^5String 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​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:中国重汽营销越发“人性化”,走近用户就不会错!
下一篇:[leetcode] 404. Sum of Left Leaves
相关文章

 发表评论

暂时没有评论,来抢沙发吧~