Given a string that consists of only ‘L’, ‘R’, and ‘X’ characters. You need to determine if the string can be transformed into another string by swapping adjacent ‘L’ and ‘X’, or ‘R’ and ‘X’. The ‘L’ can only move to the left and ‘R’ can only move to the right.
def canTransform(start: str, end: str) -> bool:
# Check if both strings have the same number of 'L's and 'R's
if start.replace('X', '') != end.replace('X', ''):
return False
# Check positions of 'L'
t = [(i, c) for i, c in enumerate(start) if c != 'X']
e = [(i, c) for i, c in enumerate(end) if c != 'X']
for (i, c1), (j, c2) in zip(t, e):
if c1 != c2:
return False
if c1 == 'L' and i < j:
return False
if c1 == 'R' and i > j:
return False
return True
# Example usage:
start = "RXXLRXRXL"
end = "XRLXXRRLX"
print(canTransform(start, end)) # Output: True
This efficiently checks all the transformation constraints. If you have any specific edge cases or further details, do let me know!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?