leetcode-838-Push Dominoes
问题
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:
1 | Input: ".L.R...LR..L.." |
Example 2:
1 | Input: "RR.L" |
Note:
0 <= N <= 10^5
- String
dominoes
contains only'L
‘,'R'
and'.'
分析
思路1: 对 dominoes
进行两边扫描,统计每个位置距离左边的 R
或右边的 L
的最短的距离。正号代表距离 R
的距离,负号代表距离 L
的距离。
思路2: 分析可知,我们只需要更新每个点的状态,而每一组连续的点...
,取决于其左边的 R
或 L
以及右边的 R
或 L
。则对于每一对连续 ...
状态及转化有一下四种:
R...R
-> RRRRR
L...L
-> LLLLLL
R...L
-> RR.LL
L...R
-> L...R
于是可以对 dominoes
进行一边遍历并对每一段...
的情况进行判断从而得到最终的答案。
代码1
1 | class Solution { |
代码2
1 | // 虽然这个只有一次遍历,但运行时间比上一个仿佛慢了不少 |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/27/leetcode-838/
License: 知识共享署名-非商业性使用 4.0 国际许可协议