Skip to content

Commit 34ea610

Browse files
authored
Create 838. Push Dominoes (#784)
2 parents 65c81d0 + adf2265 commit 34ea610

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

838. Push Dominoes

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public:
3+
string pushDominoes(string dominoes) {
4+
string ans = dominoes;
5+
vector<int> dist(dominoes.size(), 0);
6+
7+
int latestr = -1; // last index of 'R'
8+
char last = '.'; // last force seen
9+
10+
// First pass: handle 'R' forces from left to right
11+
for (int i = 0; i < dominoes.size(); i++) {
12+
if (dominoes[i] == 'R') {
13+
latestr = i;
14+
last = 'R';
15+
} else if (dominoes[i] == '.' && latestr != -1 && last == 'R') {
16+
dist[i] = abs(latestr - i);
17+
ans[i] = 'R';
18+
} else {
19+
last = 'L'; // force blocked by L
20+
}
21+
}
22+
23+
last = '.';
24+
int latestl = dominoes.size(); // last index of 'L'
25+
int d = 0;
26+
27+
// Second pass: handle 'L' forces from right to left
28+
for (int i = dominoes.size() - 1; i >= 0; i--) {
29+
if (dist[i] == -1) continue; // skip already pushed by 'R'
30+
31+
if (dominoes[i] == 'L') {
32+
latestl = i;
33+
last = 'L';
34+
} else if (dominoes[i] == '.' && last == 'L') {
35+
d = abs(latestl - i);
36+
if (dist[i] == 0 || d < dist[i]) {
37+
ans[i] = 'L';
38+
} else if (d == dist[i]) {
39+
ans[i] = '.'; // equal push from both sides
40+
}
41+
} else {
42+
last = 'R'; // force blocked by R
43+
}
44+
}
45+
46+
return ans;
47+
}
48+
};

0 commit comments

Comments
 (0)