#777
Medium Algorithms Swap adjacent in lr string
Two Pointers String
37.9% acceptance
Feb 21, 2026
1334
955
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 result, return True if and only if there exists a sequence of moves to transform start to result.
Solution
Rust
Time O(n²)
Space O(1)
/*
* 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 result, return True if and only if there exists a sequence of moves to transform start to result.
* Example 1:
* Input: start = "RXXLRXRXL", result = "XRLXXRRLX"
* Output: true
* Explanation: We can transform start to result following these steps:
* RXXLRXRXL ->
* XRXLRXRXL ->
* XRLXRXRXL ->
* XRLXXRRXL ->
* XRLXXRRLX
* Example 2:
* Input: start = "X", result = "L"
* Output: false
* Constraints:
* 1 <= start.length <= 104
* start.length == result.length
* Both start and result will only consist of characters in 'L', 'R', and 'X'.
*/
impl Solution {
pub fn can_transform(start: String, result: String) -> bool {
let n = start.len();
let sb = start.as_bytes();
let rb = result.as_bytes();
let s_non: Vec<u8> = sb.iter().filter(|&&c| c != b'X').cloned().collect();
let r_non: Vec<u8> = rb.iter().filter(|&&c| c != b'X').cloned().collect();
if s_non != r_non { return false; }
let mut i = 0;
let mut j = 0;
loop {
while i < n && sb[i] == b'X' { i += 1; }
while j < n && rb[j] == b'X' { j += 1; }
if i == n && j == n { return true; }
if i == n || j == n { return false; }
if sb[i] == b'L' && i < j { return false; }
if sb[i] == b'R' && i > j { return false; }
i += 1;
j += 1;
}
}
}