-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathPushDominoes.java
54 lines (48 loc) · 1.29 KB
/
PushDominoes.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public String pushDominoes(String dominoes) {
int n = dominoes.length();
int[] left = new int[n];
int nearestLeftIndex = -1;
for(int i=n-1;i>=0;i--){
char c = dominoes.charAt(i);
if(c == 'L'){
nearestLeftIndex = i;
}
else if(c == 'R'){
nearestLeftIndex = -1;
}
left[i] = nearestLeftIndex;
}
int[] right = new int[n];
int nearestRigtIndex = -1;
for(int i=0;i<n;i++){
char c = dominoes.charAt(i);
if(c == 'L'){
nearestRigtIndex = -1;
}
else if(c == 'R'){
nearestRigtIndex = i;
}
right[i] = nearestRigtIndex;
}
char[] ans = new char[n];
for(int i=0;i<n;i++){
if(dominoes.charAt(i) == '.'){
int nearestLeft = left[i];
int nearestRight = right[i];
int leftDiff = nearestLeft == -1 ? Integer.MAX_VALUE : Math.abs(nearestLeft - i);
int rightDiff = nearestRight == -1 ? Integer.MAX_VALUE : Math.abs(nearestRight - i);
if(leftDiff == rightDiff){
ans[i] = '.';
} else if(leftDiff < rightDiff){
ans[i] = 'L';
} else if(leftDiff > rightDiff){
ans[i] = 'R';
}
} else {
ans[i] = dominoes.charAt(i) ;
}
}
return new String(ans);
}
}