Problem description:

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:

1
2
3
4
5
6
7
8
9
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’}.

Solution:

In the given string start, L can move to the left but can’t pass through R, R can move to the right but can’t pass through L. Basically, there are 4 situations (when start[i] != ‘X’ and end[j] != ‘X’):

  • start[i] != end[j] return false, cause L and R can’t pass through each other.
  • start[i] == ‘L’ && j > i return false, cause L can’t move to the right.

    • RX XR: true
    • XR RX: falase
  • start[i] == ‘R’ && j < i return false cause R can’t move to the left.

    • XL LX: true
    • LX XL: false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
bool canTransform(string s, string t) {
if(s.length() != t.length()) return false;

for(int i= 0, j= 0; i< s.length(), j< t.length();){
if(s[i] == 'X') i++;
if(t[j] == 'X') j++;

if(s[i] != 'X' && t[j] != 'X'){
if(s[i] != t[j]) return false;
else if(s[i] == 'L' && j> i) return false;
else if(s[i] == 'R' && i> j) return false;
else{
//printf("%c, %c, %d, %d\n", s[i], t[j], i, j);
i++, j++;
}
}
}
return true;
}
};

time complexity: $O(n)$
space complexity: $O(1)$
reference: