class Solution {
public:
bool canTransform(string start, string end) {
string startNoX, endNoX;
removeX(start, startNoX);
removeX(end, endNoX);
if (startNoX != endNoX) {
return false;
}
vector<int> startLIdx, endLIdx;
getIndices(start, end, startLIdx, endLIdx, 'L');
for (int i = 0; i < startLIdx.size(); ++i) {
if (endLIdx[i] > startLIdx[i]) {
return false;
}
}
vector<int> startRIdx, endRIdx;
getIndices(start, end, startRIdx, endRIdx, 'R');
for (int i = 0; i < startRIdx.size(); ++i) {
if (endRIdx[i] < startRIdx[i]) {
return false;
}
}
return true;
}
private:
void removeX(string &s, string &noX) {
for (auto &c : s) {
if (c != 'X') {
noX.push_back(c);
}
}
}
void getIndices(string &start, string &end,
vector<int> &startIdx, vector<int> &endIdx, char c) {
for (int i = 0; i < start.size(); ++i) {
if (start[i] == c) {
startIdx.push_back(i);
}
if (end[i] == c) {
endIdx.push_back(i);
}
}
}
};
class Solution {
public:
bool canTransform(string start, string end) {
string startNoX, endNoX;
removeX(start, startNoX);
removeX(end, endNoX);
if (startNoX != endNoX) {
return false;
}
vector<int> startRIdx, startLIdx, endRIdx, endLIdx;
for (int i = 0; i < start.size(); ++i) {
if (start[i] == 'R') {
startRIdx.push_back(i);
} else if (start[i] == 'L') {
startLIdx.push_back(i);
}
if (end[i] == 'R') {
endRIdx.push_back(i);
} else if (end[i] == 'L') {
endLIdx.push_back(i);
}
}
#if 1
for (int i = 0; i < startRIdx.size(); ++i) {
if (startRIdx[i] > endRIdx[i]) {
return false;
}
}
#endif
for (int i = 0; i < startLIdx.size(); ++i) {
if (startLIdx[i] < endLIdx[i]) {
return false;
}
}
return true;
}
private:
void removeX(string &org, string &noX) {
for (char &c : org) {
if (c != 'X') {
noX.push_back(c);
}
}
}
};
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up