问题:
难度:medium
说明:
给出一个字符,字符只包含 'L' 'R' '.' 三种字符,其实整个数组是表示一个多米诺骨牌状态, L 表示当前的骨牌处于 左倒 状态, R 表示骨牌 右倒 状态,. 表示树立,没有倒下的状态。
要求当前给出的数组状态,求出最终的多米诺骨牌状态,设定所有骨牌倒下运动速度一样。
题目连接:https://leetcode.com/problems/push-dominoes/
输入范围:
n == dominoes.length
1 <= n <= 105
dominoes[i]
is either'L'
,'R'
, or'.'
.
输入案例:
Example 1:
Input: dominoes = "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Example 2:
Input: dominoes = ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
我的代码:
其实可以当做滑动窗口处理,不过主要是很多细节地方要注意,比如要保留往右倒下的起始点,又要判断右倒下起始点是否不存在,等等,这块考的还是细节的逻辑。
Java:
class Solution {
public String pushDominoes(String dominoes) {
int Ridx = -1;
char[] chs = dominoes.toCharArray();
for(int i = 0, len = dominoes.length(); i < len; ) {
if(chs[i] == 'L') {
int j = i, begin = Ridx == -1 ? -1 : (i + Ridx >> 1);
while(-- j >= 0 && ((chs[j] != 'R' || j > begin) && chs[j] != 'L'))
chs[j] = 'L';
if(begin != -1 && j >= begin && ((i + Ridx) & 1) == 0)
chs[begin] = Ridx != -1 && begin != Ridx ? '.' : 'L';
Ridx = i;
i ++;
} else if(chs[i] == 'R') {
Ridx = i;
while(++ i < len && chs[i] == '.') chs[i] = 'R';
} else i ++;
}
return new String(chs);
}
}
C++:
class Solution {
public:
string pushDominoes(string dominoes) {
int Ridx = -1, begin = -1, j = -1;
for(int i = 0, len = dominoes.length(); i < len;) {
if(dominoes[i] == 'L') {
j = i, begin = Ridx == -1 ? -1 : ((Ridx + i) >> 1);
while(-- j >= 0 && ((dominoes[j] != 'R' || j > begin) && dominoes[j] != 'L'))
dominoes[j] = 'L';
if(begin != -1 && j >= begin && ((Ridx + i) & 1) == 0)
dominoes[begin] = Ridx != -1 && begin != Ridx ? '.' : 'L';
Ridx = i;
i ++;
} else if(dominoes[i] == 'R') {
Ridx = i;
while(++ i < len && dominoes[i] == '.') dominoes[i] = 'R';
} else i ++;
}
return dominoes;
}
};