Swap Adjacent in LR String
We can determine if we can transform the start
string into the end
string using the given moves by following these insights:
Character Counts: The number of ‘L’ and ‘R’ characters must be the same in both the
start
andend
strings.Character Positions: The ‘R’ characters in the
start
string should not move to the left in theend
string, and the ‘L’ characters should not move to the right.
With these insights in mind, we can create an algorithm:
Check Lengths: If the lengths of the
start
andend
strings are not the same, returnFalse
.Check Character Counts: If the counts of ‘L’ and ‘R’ in both strings are not the same, return
False
.Check Positions: Iterate through the
start
andend
strings simultaneously and compare the positions of ‘L’ and ‘R’.
Here’s the code:
|
|
The code returns True
if we can transform the start
string into the end
string using the given moves, otherwise False
. It has a time complexity of O(n), where n is the length of the strings, and space complexity is O(1).