777. Swap Adjacent in LR String

https://leetcode.com/problems/swap-adjacent-in-lr-string/

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

 

Constraints:

  • 1 <= len(start) == len(end) <= 10000.
  • Both start and end will only consist of characters in {'L', 'R', 'X'}.
---


---
class Solution {
public boolean canTransform(String start, String end) {
// relative order or L R should be same
if (!start.replace("X","").equals(end.replace("X",""))) {
return false;
}
int p1 = 0, p2 = 0;
while (p1 < start.length() && p2 < end.length()) {
while (p1 < start.length() && start.charAt(p1) == 'X') {
p1++;
}
while (p2 < end.length() && end.charAt(p2) == 'X') {
p2++;
}
if (p1 == start.length() || p2 == end.length()) {
return p1 == start.length() && p2 == end.length();
}
// L cannot be after in end state
if (start.charAt(p1) == 'L' && p2 > p1) {
return false;
}
// R cannot be before in end state
if (start.charAt(p1) == 'R' && p1 > p2) {
return false;
}
p1++;
p2++;
}
return true;
}
}