一行中有 N 张多米诺骨牌,我们将每张多米诺骨牌垂直竖立。
在开始时,我们同时把一些多米诺骨牌向左或向右推。
每过一秒,倒向左边的多米诺骨牌会推动其左侧相邻的多米诺骨牌。
同样地,倒向右边的多米诺骨牌也会推动竖立在其右侧的相邻多米诺骨牌。
如果同时有多米诺骨牌落在一张垂直竖立的多米诺骨牌的两边,由于受力平衡, 该骨牌仍然保持不变。
就这个问题而言,我们会认为正在下降的多米诺骨牌不会对其它正在下降或已经下降的多米诺骨牌施加额外的力。
给定表示初始状态的字符串 "S" 。如果第 i 张多米诺骨牌被推向左边,则 S[i] = 'L';如果第 i 张多米诺骨牌被推向右边,则 S[i] = 'R';如果第 i 张多米诺骨牌没有被推动,则 S[i] = '.'。
返回表示最终状态的字符串。
示例 1:
输入:".L.R...LR..L.."
输出:"LL.RR.LLRRLL.."
示例 2:
输入:"RR.L"
输出:"RR.L"
说明:第一张多米诺骨牌没有给第二张施加额外的力。
提示:
0 <= N <= 10^5
表示多米诺骨牌状态的字符串只含有 'L','R'; 以及 '.';
思路:遍历两次,第一次从左往右遍历记录每个竖直放置的多米诺骨牌左边最近的‘R’到它的距离,第二次从右往左遍历记录每个竖直放置的多米诺骨牌右边最近的‘L’到它的距离。
class Solution {
public String pushDominoes(String dominoes) {
int time=0;
int[] arr=new int[dominoes.length()];
for(int i=0;i<dominoes.length();i++) {
if(dominoes.charAt(i)=='R')
time=1;
else if(dominoes.charAt(i)=='.' && time>0)
arr[i]=time++;
else
time=0;
}
time=0;
for(int i=dominoes.length()-1;i>=0;i--) {
if(dominoes.charAt(i)=='R')
time=0;
else if(dominoes.charAt(i)=='L')
time=1;
else if(time>0){
if(arr[i]==0) arr[i]=-time;
else if(arr[i]>time) {
arr[i]=-time;
time++;
}
else if(arr[i]==time)
arr[i]=0;
}
}
StringBuilder str=new StringBuilder();
for(int i=0;i<dominoes.length();i++) {
if(arr[i]==0)
str.append(dominoes.charAt(i));
else if(arr[i]<0)
str.append('L');
else
str.append('R');
}
return str.toString();
}
}