777. Swap Adjacent in LR String
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
9Input: 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 | class Solution { |
time complexity: $O(n)$
space complexity: $O(1)$
reference: