777. 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 1:

Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: true
Explanation: We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

Example 2:

Input: start = "X", end = "L"
Output: false

Example 3:

Input: start = "LLR", end = "RRL"
Output: false

Example 4:

Input: start = "XL", end = "LX"
Output: true

Example 5:

Input: start = "XLLR", end = "LXLX"
Output: false

 

Constraints:

  • 1 <= start.length <= 104
  • start.length == end.length
  • Both start and end will only consist of characters in 'L', 'R', and 'X'.

Rust Solution

struct Solution;

impl Solution {
    fn can_transform(start: String, end: String) -> bool {
        let mut iter_a = start.chars();
        let mut iter_b = end.chars();
        let mut count_a = 0;
        let mut count_b = 0;
        while let (Some(mut a), Some(mut b)) = (iter_a.next(), iter_b.next()) {
            while a == 'X' {
                count_a += 1;
                a = if let Some(c) = iter_a.next() { c } else { 'Y' };
            }
            while b == 'X' {
                count_b += 1;
                b = if let Some(c) = iter_b.next() { c } else { 'Y' };
            }
            if a != b {
                return false;
            }
            if a == 'R' && count_a > count_b {
                return false;
            }
            if a == 'L' && count_a < count_b {
                return false;
            }
        }
        true
    }
}

#[test]
fn test() {
    let start = "RXXLRXRXL".to_string();
    let end = "XRLXXRRLX".to_string();
    let res = true;
    assert_eq!(Solution::can_transform(start, end), res);
    let start = "XXRXXLXXXX".to_string();
    let end = "XXXXRXXLXX".to_string();
    let res = false;
    assert_eq!(Solution::can_transform(start, end), res);
}

Having problems with this solution? Click here to submit an issue on github.