解题思路:
一道非常有价值的模拟题,首先要确定切入点,如何判断倒下去的方向。对于每个.,倒下去的方向是和左右两边最近的倒下去骨牌有关,都是左,那么就往左倒,都是右就往右倒,左右就往中间倒,右左不动即可。根据这个模拟的思路,首先初始左方向为R(为了应对开始的连续.序列,这样遇到R就直接跳过了),然后根据上面的逻辑进行判断和分别处理,注释已经很详尽了,代码如下:
class Solution {
public:
string pushDominoes(string dominoes) {
int index = 0, n = dominoes.size();
char pre = 'L';
while(index < n) {
int temp = index;
// 跳过连续的.
while(temp < n && dominoes[temp] == '.') {
temp ++;
}
// 以连续.结尾标记为R就不会往中间倒
char cur = temp < n ? dominoes[temp] : 'R';
// 如果倒的方向相同
if(pre == cur) {
while(index < temp) {
dominoes[index ++] = cur;
}
} else if(pre == 'R' && cur == 'L') {// 向中间倒
int k = temp - 1;
while(index < k) {
dominoes[k --] = 'L';
dominoes[index ++] = 'R';
}
}
index = temp + 1;
pre = cur;
}
return dominoes;
}
};