777. Swap Adjacent in LR String - cocoder39/coco39_LC GitHub Wiki

777. Swap Adjacent in LR String

  • XL -> LX: XXXL -> LXXX
  • RX -> XR: RXXX -> XXXR

Thinking process:

    1. start.replace('X', '') != end.replace('X', '') ensures L and R align in sequence and count in the 2 strings
    1. now we want to insert X properly such that start can transform to end
    • when inserting a X to left of L in start, then a X should be inserted to right of the matching L in end
    • when inserting a X to right of R in start, then a X should be inserted to left of the matching R in end
    • image
  • 3: len(start) == len(end) so equal length of X are inserted into start and end
class Solution:
    def canTransform(self, start: str, end: str) -> bool:
        # if can transform, then string with X removed should be same 
        # this ensures L and R align in sequence and count  
        # "RXR" -> "XXR"       
        if start.replace('X', '') != end.replace('X', ''):
            return False

        i, j = 0, 0
        n = len(start)

        # ensure L and R adheres to the movement constraints
        # L can only move left and R can only move right
        while i < n and j < n:
            while i < n and start[i] == 'X':
                i += 1
            
            while j < n and end[j] == 'X':
                j += 1
            
            if i == n and j == n:
                return True
            
            if i == n or j == n:
                return False
            
            if start[i] != end[j]:
                return False
            
            # RXX -> XRX -> XXR
            if start[i] == 'R' and i > j:
                return False
            
            # XXL -> XLX -> LXX 
            if start[i] == 'L' and i < j:
                return False

            i += 1
            j += 1

        # we reach here only if at least one string has been processed
        # as we have validated the 2 strings has L and R align in sequence and count, this means we have processed all L and R in the other string
        # there could be extra X in the other string, but string1 and string2 have equal length so there is at most one extra R in the other string
        return True