838: Push-Dominoes
Medium
Basically, for my solution of Push Dominoes
, I did
not want to back-track on any of the decisions that I made
previously; meaning I wanted to swap-in the correct letters in
just one-iteration.
To do this, I believed it was necessary to compute all the
indices for the dominoes
pushed Left
,
left_indices
, and all the indices for the
dominoes
pushed Right
,
right_indices
. I also added index 0
to
the beginning of left_indices
, and added index
dominoes.size()
to the end of
right_indices
.
Then, if you have an iterator, l
iterating through
left_indices
and r
iterating through
right_indices
, you have 3 possible
outcomes:
Finally, we break out of the while
loop if
l
or r
exceeds
left_indices.size()
or
right_indices.size()
respectively. However, if there
exists r
such that
r < right_indices.size()
, we can just iterate
between right_indices[r]
and
dominoes.size()
and set them all to
R
.
Code:
class Solution {
public:
(string dominoes) {
string pushDominoes<int> left_indices;
vector.push_back(0);
left_indices<int> right_indices;
vector
for (int i = 0; i < dominoes.size(); ++i) {
if (dominoes[i] == 'L') {
.push_back(i);
left_indices} else if (dominoes[i] == 'R') {
.push_back(i);
right_indices}
}
.push_back(dominoes.size());
right_indices
int l = 1, r = 0;
for (; l < left_indices.size() && r < right_indices.size();) {
for (; l < left_indices.size() && left_indices[l] < right_indices[r];) {
for (int i = left_indices[l-1]; i < left_indices[l]; ++i) {
[i] = 'L';
dominoes}
++l;
}
for (; l < left_indices.size() && r+1 < right_indices.size() && right_indices[r+1] < left_indices[l];) {
for (int i = right_indices[r]; i < right_indices[r+1]; ++i) {
[i] = 'R';
dominoes}
++r;
}
if (l < left_indices.size() && r < right_indices.size() && right_indices[r] < left_indices[l]) {
for (int i = 1; i < (left_indices[l]-right_indices[r]+1)/2; ++i) {
[left_indices[l]-i] = 'L';
dominoes[right_indices[r]+i] = 'R';
dominoes}
++l;
++r;
}
}
if (r < right_indices.size()) {
for (int i = right_indices[r]+1; i < dominoes.size(); ++i) {
[i] = 'R';
dominoes}
}
return dominoes;
}
};