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 stringstartand the ending stringend, returnTrueif 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'}.
2. Implementation
(1) Two Pointers
classSolution {publicbooleancanTransform(String start,String end) {if (start.length() !=end.length()) {returnfalse; } int countX1 =0, countX2 =0;int index1 =0, index2 =0;while (index1 <start.length() && index2 <end.length()) {// Get the first non x character in start string, and count the number of X while (index1 <start.length() &&start.charAt(index1) =='X') {++countX1;++index1; }// Get the first non x character in end string, and count the number of Xwhile (index2 <end.length() &&end.charAt(index2) =='X') {++countX2;++index2; }// Both strings get to the end, return true;if (index1 ==start.length() && index2 ==end.length()) {returntrue; }// One of the string is running out of character, return false;elseif (index1 ==start.length() || index2 ==end.length()) {returnfalse; }// If the first non x character are different, since L will only get to left, and R can only get to right,// there is no way for start string to be transformed into end stringelseif (start.charAt(index1) !=end.charAt(index2)) {returnfalse; }// L can only get to left, if number of x in start is less than number of x in end string, it is impossible for e// start string to be transformed into end stringelseif (start.charAt(index1) =='L'&& countX1 < countX2) {returnfalse; }// R can only get tor right, if number of x in start is greater than the number of x in end string, it is impossible // start string to be transformed into end stringelseif (start.charAt(index1) =='R'&& countX1 > countX2) {returnfalse; }else {++index1;++index2; } }returntrue; }}