Swap Adjacent In LR String Problem


Description

LeetCode Problem 777.

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:

1
2
3
4
5
6
7
8
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: true
Explanation: We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

Constraints:

  • 1 <= start.length<= 10^4
  • start.length == end.length
  • Both start and end will only consist of characters in ‘L’, ‘R’, and’X’.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    bool canTransform(string start, string end) {
        int n = start.size();
        string s1, s2;
        for (int i = 0; i < n; ++i) 
            if (start[i] != 'X') 
            	s1 += start[i];
        for (int i = 0; i < n; ++i) 
            if (end[i] != 'X') 
            	s2 += end[i];
        if (s1 != s2) 
        	return false;
        for (int i = 0, j = 0; i < n && j < n;) {
            if (start[i] == 'X') 
               i++;
            else if (end[j] == 'X') 
               j++;
            else {
                if ((start[i] == 'L' && i < j) || (start[i] == 'R' && i > j)) 
                	return false;
                i++;
                j++;
            }
        }
        return true;
    }
};




Related Posts

Squares Of A Sorted Array Problem

LeetCode 977. Given an integer array nums sorted in non-decreasing...

Sort Array By Parity Problem

LeetCode 905. Given an integer array nums, move all the...

Sort Array By Parity II Problem

LeetCode 922. Given an array of integers nums, half of...

Shortest Distance To A Character Problem

LeetCode 821. Given a string s and a character c...

Reverse Only Letters Problem

LeetCode 917. Given a string s, reverse the string according...

Push Dominoes Problem

LeetCode 838. There are n dominoes in a line, and...