838: Push-Dominoes
Medium
table of contents
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 pushDominoes(string dominoes) {
vector<int> left_indices;
left_indices.push_back(0);
vector<int> right_indices;
for (int i = 0; i < dominoes.size(); ++i) {
if (dominoes[i] == 'L') {
left_indices.push_back(i);
} else if (dominoes[i] == 'R') {
right_indices.push_back(i);
}
}
right_indices.push_back(dominoes.size());
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) {
dominoes[i] = 'L';
}
++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) {
dominoes[i] = 'R';
}
++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) {
dominoes[left_indices[l]-i] = 'L';
dominoes[right_indices[r]+i] = 'R';
}
++l;
++r;
}
}
if (r < right_indices.size()) {
for (int i = right_indices[r]+1; i < dominoes.size(); ++i) {
dominoes[i] = 'R';
}
}
return dominoes;
}
};