Problem Statement

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:

Problem Link

https://leetcode.com/problems/swap-adjacent-in-lr-string/description/

Code

class Solution {
public:
    bool canTransform(string start, string end) {

        int n = start.size();

        int p1 = 0, p2 = 0;

        while(p1<n || p2<n) {
            
            // get the non-X positions of 2 strings
            while(p1<n&&start[p1]=='X') {
                p1++;
            }

            while(p2<n&&end[p2]=='X') {
                p2++;
            }

            //if both of the pointers reach the end the strings are transformable
            if(p1==n&&p2==n) {
                return true;
            }

            // if only one of the pointer reach the end they are not transformable
            if(p1>=n||p2>=n) {
                return false;
            }

            
            if(start[p1]!=end[p2]) {
                return false;
            }

            
            // if the character is 'L', it can only be moved to the left. p1 should be greater or equal to p2.
            if(start[p1]=='R'&&p2<p1) {
                return false;
            }

            
            // if the character is 'R', it can only be moved to the right. p2 should be greater or equal to p1.
            if(start[p1]=='L'&&p1<p2) {
                return false;
            }

            p1++;
            p2++;

        }

        return true;
        

       
        
    }
};