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
Constraints:
1 <= len(start) == len(end) <= 10000
.- Both start and end will only consist of characters in
{'L', 'R', 'X'}
.
思路:發現規律:
// R 只能右邊移動, R不能跳過L和R
// L 只能左邊移動;L不能跳過L和R
// 而且所有R,L去掉X之後的相對順序和個數不能變
雙指針,掃描到不是X的地方,判斷相對性,R和L一定要相同,而且座標,R p2不能小於P1,L,p2不能大於p1
class Solution {
// R 只能右邊移動, R不能跳過L和R
// L 只能左邊移動;L不能跳過L和R
// 而且所有R,L去掉X之後的相對順序和個數不能變
public boolean canTransform(String start, String end) {
if(!start.replace("X", "").equals(end.replace("X", ""))) {
return false;
}
if(start.length() != end.length()) {
return false;
}
int p1 = 0; int p2 = 0;
while(p1 < start.length() && p2 < end.length()) {
// get Non X position;
while(p1 < start.length() && start.charAt(p1) == 'X') {
p1++;
}
while(p2 < end.length() && end.charAt(p2) == 'X') {
p2++;
}
if(p1 == start.length() && p2 == end.length()) {
return true;
}
if(p1 == start.length() || p2 == end.length()) {
return false;
}
if(start.charAt(p1) != end.charAt(p2)) {
return false;
}
if(start.charAt(p1) =='L' && p2 > p1) {
return false;
}
if(start.charAt(p1) == 'R' && p2 < p1) {
return false;
}
p1++;
p2++;
}
return true;
}
}