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'}
.
分析
这一题只需要记住一个规律即可,R一定要向右找,所以end里面的R的位置不能在start的左边。L一定是向左找,所以end
里面L的位置一定不能在start的右边。满足上述条件,那么start可以通过变化得到end。所以我们只需要判断R/L在start和end中的位置即可。维护两个下标s1和e1分别代表非X的位置。
举例说明:
start | X | L | X | R | R | X | X | R | X | X |
end | L | X | X | X | X | X | X | R | R | R |
s1 | 1 | |||||||||
e1 | 0 | |||||||||
s1 | 3 | |||||||||
e1 | 7 | |||||||||
s1 | 4 | |||||||||
e1 | 8 | |||||||||
s1 | 5 | |||||||||
e1 | 9 |
第一次寻找非X的位置得到s1 = 1, e1=0,那么此时为L,并且s1>e1,那么一定说明L通过左移可以与end匹配。
此时s1,p1继续向右寻找,寻找下一个非X的值,s1=3, e1=7,且s1 < e1,此时为R,那么说明R可以通过右移与end匹配。
一旦有不满足的条件,或者两个非X值不等,则直接返回False。
Code
class Solution {
public:
bool canTransform(string start, string end) {
int len = start.size();
if (end.size() != len)
return false;
int s1 = 0;
int e1 = 0;
while (true)
{
while (s1 < len && start[s1] == 'X')
s1 ++;
while (e1 < len && end[e1] == 'X')
e1 ++;
cout << s1 << " " << e1<<endl;
if (s1 == len && e1 == len)return true;
if (s1 == len && e1 != len)return false;
if (s1 != len && e1 == len)return false;
if (start[s1] != end[e1] ||
(start[s1] == 'L' && s1 < e1) ||
(start[s1] == 'R' && s1 > e1))
return false;
s1 ++;
e1 ++;
}
return true;
}
};
运行效率
Runtime: 20 ms, faster than 18.69% of C++ online submissions for Swap Adjacent in LR String.
Memory Usage: 9.5 MB, less than 82.30% of C++ online submissions for Swap Adjacent in LR String.