forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPush Dominoes.java
40 lines (40 loc) · 1.37 KB
/
Push Dominoes.java
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
37
38
39
40
// Runtime: 11 ms (Top 100.00%) | Memory: 43.4 MB (Top 96.04%)
// Time complexity: O(N)
// Space complexity: O(N), where N is the length of input string
class Solution {
public String pushDominoes(String dominoes) {
// ask whether dominoes could be null
final int N = dominoes.length();
if (N <= 1) return dominoes;
char[] res = dominoes.toCharArray();
int i = 0;
while (i < N) {
if (res[i] == '.') {
i++;
} else if (res[i] == 'L') { // push left
int j = i-1;
while (j >= 0 && res[j] == '.') {
res[j--] = 'L';
}
i++;
} else { // res[i] == 'R'
int j = i+1;
while (j < N && res[j] == '.') { // try to find 'R' or 'L' in the right side
j++;
}
if (j < N && res[j] == 'L') { // if found 'L', push left and right
for (int l = i+1, r = j-1; l < r; l++, r--) {
res[l] = 'R';
res[r] = 'L';
}
i = j + 1;
} else { // if no 'L', push right
while (i < j) {
res[i++] = 'R';
}
}
}
}
return String.valueOf(res);
}
}