In a string composed of de >'L'de>, de >'R'de>, and de >'X'de> characters, like de >"RXXLRXRXL"de>, a move consists of either replacing one occurrence of de >"XL"de> with de >"LX"de>, or replacing one occurrence of de >"RX"de> with de >"XR"de>. Given the starting string de >startde> and the ending string de >endde>, return de >Truede> 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:
- de >1 <= len(start) = len(end) <= 10000de>.
- Both start and end will only consist of characters in de >{'L', 'R', 'X'}de>.
根据题目的描述,L和R可以移动,因此只需要start和end这两个字符串里L和R的相对位置相同就可以。又考虑到,L只能向左移动,R只能向右移动,因此对应位置的L,start中的L只能在end中L的右边(或者同一位置),对应位置的R,start中的R只能在end中的R的左边(或者同一位置),代码如下:
class Solution {
public boolean canTransform(String start, String end) {
char[] chs = start.toCharArray(), che = end.toCharArray();
if(chs.length != end.length())
return false;
int i = 0, j = 0, len = chs.length;
while(true){
while(i < chs.length && chs[i] == 'X')
i++;
while(j < che.length && che[j] == 'X')
j++;
//System.out.println(i + " " + j);
if(i == len && j == len)
return true;
if(i == len || j == len)
return false;
if(chs[i] != che[j])
return false;
if(chs[i] == 'R' && i > j || chs[i] == 'L' && i < j)
return false;
i++;j++;
}
}
}