题目链接
思路一:广度优先搜索
分析:每个骨牌的倒伏状态只和周围的骨牌受力状态有关,那么我们首先拿到所有在一开始受力的骨牌,并且记录一下方向,把这些最开始受力的骨牌放到队列中,然后进行广度搜索即可。每个骨牌的下一个骨牌就是在当前骨牌受力方向的下一个。
代码:
class Solution {
public String pushDominoes(String dominoes) {
char[] cs = dominoes.toCharArray();
Queue<int[]> queue = new LinkedList<>();// location,forwarding,time 当前位置,受力方向,时间
int[] ts = new int[cs.length];//记录是第几次受力
for(int i =0; i<cs.length;i++){
if(cs[i]=='.') continue;
int forwarding = cs[i] == 'L' ? -1 : 1;
queue.add(new int[]{i,forwarding,1});
ts[i] = 1;
}
while (!queue.isEmpty()){
int[] top = queue.poll();
int nextLoc = top[0] + top[1];
//如果当前是'.'那么说明肯定是之前多次受力调整回来了
//下一次位置不能出界
if(cs[top[0]]=='.' || nextLoc<0 || nextLoc>=cs.length) continue;
if(ts[nextLoc] == 0){// 首次受力
queue.add(new int[]{nextLoc,top[1],top[2]+1});
cs[nextLoc] = top[1] == -1 ? 'L' : 'R';
ts[nextLoc] = top[2] + 1;
} else if(ts[nextLoc] == top[2] + 1){//同一时刻 多次受力
//恢复直立状态
cs[nextLoc] = '.';
}
}
return String.valueOf(cs);
}
}
思路二:双指针+模拟
分析:只有是’.'的才有可能被更改,那么我们可以总结出这么几种情况
- L…L
- R…R
- R…L
还有一种L…R的情况,不过中间的是不需要变的。
现在问题在于我们需要找到一段连续的…,我们可以用两个指针指向这段连续的…,我这里使用的是左闭右开区间。
当找到这段连续的…后,那么就根据上面的三种情况分别进行处理即可。
代码:
public String pushDominoes(String dominoes) {
char[] cs = dominoes.toCharArray();
int len = cs.length;
for(int i = 0; i < len; i++){
if(cs[i]=='.'){
int l = i;
while (i < len && cs[i]=='.'){
i++;
}
int r = i;
if(l==0 || cs[l-1]=='L'){
if(r<len && cs[r]=='L'){// L....L
for(int j = l; j < r;j++){
cs[j] = 'L';
}
}
}else{// cs[l-1]=='R'
if(r<len && cs[r]=='R'){// R....R
for(int j = l; j<r;j++){
cs[j] = 'R';
}
}else{//R ..... L
while (l<r-1){
cs[l] = 'R';
cs[r-1] = 'L';
l++;
r--;
}
}
}
}
}
return String.valueOf(cs);
}