777. Swap Adjacent in LR String
https://leetcode.com/problems/swap-adjacent-in-lr-string/
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:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX" Output: True Explanation: We can transform start to end following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX
Note:
1 <= len(start) = len(end) <= 10000
.- Both start and end will only consist of characters in
{'L', 'R', 'X'}
.
---
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean canTransform(String start, String end) { | |
if (start.length() != end.length()) { | |
return false; | |
} | |
int i = 0, j = 0; | |
while (i < start.length() && j < end.length()) { | |
// Find first non X character | |
while (i < start.length() && start.charAt(i) == 'X') { | |
i++; | |
} | |
while (j < end.length() && end.charAt(j) == 'X') { | |
j++; | |
} | |
// Check if both reached end | |
if (i == start.length() || j == end.length()) { | |
return i == start.length() && j == end.length(); | |
} | |
if (start.charAt(i) != end.charAt(j)) { | |
return false; | |
} | |
// Check relative order, 'R' can only move to right | |
if (start.charAt(i) == 'R' && j < i) { | |
return false; | |
} | |
// Check relative order, 'L' can only move to left | |
if (start.charAt(i) == 'L' && j > i) { | |
return false; | |
} | |
i++; | |
j++; | |
} | |
return true; | |
} | |
} |