leetcode 838

问题

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.

img

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
2
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."

Example 2:

1
2
3
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 '.'

分析

思路1: 对 dominoes 进行两边扫描,统计每个位置距离左边的 R 或右边的 L 的最短的距离。正号代表距离 R 的距离,负号代表距离 L 的距离。

思路2: 分析可知,我们只需要更新每个点的状态,而每一组连续的点... ,取决于其左边的 RL 以及右边的 RL。则对于每一对连续 ... 状态及转化有一下四种:

R...R -> RRRRR

L...L -> LLLLLL

R...L -> RR.LL

L...R -> L...R

于是可以对 dominoes 进行一边遍历并对每一段... 的情况进行判断从而得到最终的答案。

代码1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
string pushDominoes(string dominoes) {
int n = dominoes.size();
vector<int> dp(n, 0);
for (int i = 0; i < n; ++i) {
if (dominoes[i] == 'L') continue;
if (dominoes[i] == 'R')
dp[i] = 1;
else {
if (i > 0 && dp[i-1] > 0)
dp[i] = dp[i-1]+1;
}
}

for (int i = n-1; i >= 0; --i) {
if (dominoes[i] == 'R') continue;
if (dominoes[i] == 'L')
dp[i] = -1;
if (i < n-1 && dp[i+1] < 0) {
int t = dp[i+1]-1;
if (dp[i] == -t)
dp[i] = 0;
else if (dp[i] > -t || dp[i] == 0)
dp[i] = t;
}
}

string ans(n, '.');
for (int i = 0; i < n; ++i) {
if (dp[i] > 0) ans[i] = 'R';
else if (dp[i] < 0) ans[i] = 'L';
}
return ans;
}
};

代码2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 虽然这个只有一次遍历,但运行时间比上一个仿佛慢了不少
class Solution {
public:
string pushDominoes(string dominoes) {
string d = 'L' + dominoes + 'R';
int n = d.size();
string ans;
for (int i = 0, j = 1; j < n; ++j) {
if (d[j] == '.') continue;
int middle = j-i-1;
if (i != 0) ans += d[i];
if (d[i] == d[j])
ans.append(middle, d[i]);
else if (d[i] == 'L' && d[j] == 'R')
ans.append(middle, '.');
else
ans += string(middle/2, 'R') + string(middle%2, '.') + string(middle/2, 'L');
i = j;
}
return ans;
}
};