In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.
Example:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX" Output: True Explanation: We can transform start to end following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX Note:
1 <= len(start) = len(end) <= 10000. Both start and end will only consist of characters in {'L', 'R', 'X'}.
// 12ms, 59%
/*
- 'L' can never move right, and 'R' can't move left
- so while comparing 'L' by 'L', if end has a 'L' with index bigger than its counterpart in start then it fails
- same rule applies to 'R'
*/
class Solution {
public:
bool canTransform(string start, string end) {
if (start.size() != end.size())
return false;
string s, e;
copy_if(start.begin(), start.end(), back_inserter(s), [](char& c) { return c != 'X'; });
copy_if(end.begin(), end.end(), back_inserter(e), [](char& c) { return c != 'X'; });
if (s != e)
return false;
int t = 0;
for (int i = 0; i < start.size(); i++) {
if (start[i] == 'L') {
while (end[t] != 'L') t++;
if (i < t++) return false;
}
}
t = end.size() - 1;
for (int i = start.size()-1; i >= 0; i--) {
if (start[i] == 'R') {
while (end[t] != 'R') t--;
if (i > t--) return false;
}
}
return true;
}
};
// 8ms, 95%
/*
- 'L' can never move right, and 'R' can't move left
*/
class Solution {
public:
bool canTransform(string start, string end) {
if (start.size() != end.size())
return false;
const int N = start.size();
int i = 0, j = 0;
while (i < N && j < N) {
while (i < N && start[i] == 'X') i++;
while (j < N && end[j] == 'X') j++;
if (i == N && j == N)
break;
if (i == N || j == N)
return false;
if (start[i] != end[j] || (start[i] == 'L' && i < j) ||
(start[i] == 'R' && i > j))
return false;
i++, j++;
}
return true;
}
};