777. Swap Adjacent in LR String
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLXbool canTransform(string start, string end) { // time: O(n); space: O(1)
int n = start.length();
for (int i = 0, j = 0; i < n && j < n; ++i, ++j) {
while (i < n && start[i] == 'X') ++i;
while (j < n && end[j] == 'X') ++j;
if (start[i] != end[j]) return false;
if ((start[i] == 'L' && i < j) || (start[i] == 'R' && i > j) ) return false;
}
return true;
}Last updated