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 1:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX" Output: true Explanation: We can transform start to end following these steps: RXXLRXRXL -> XRXLRXRXL -> XRLXRXRXL -> XRLXXRRXL -> XRLXXRRLX
Example 2:
Input: start = "X", end = "L" Output: false
Constraints:
1 <= start.length <= 104
start.length == end.length
- Both
start
andend
will only consist of characters in'L'
,'R'
, and'X'
.
题目:一串开始字符串包含L,R,和X。可以将“XL”替换为“LX”, 也可以将“RX”替换为“XR”。给定一个结束字符串,问可否通过替换操作将开始字符串转变为结束字符串。
思路:注意,题中有坑。很容易理解为“XL”和“LX”可以互相替换,“XR”和“RX”可以互相替换。其实不是的,替换是单项的,小编第一次做就理解成双向替换了T_T。再看一遍发现L字符只可以往左走,R字符只能往右走,理解到这里那就好办了。有几种情况会返回false:
1,字符串长度不相等,怎么替换也不行
2,字符串L,R,X的个数不相等,怎么替换也不行
3,字符串L, R的相对位置不一致,即去除X后两个字符串不相等。
4,end字符串中对应的L字符靠右或者对应的R字符靠左,都不可能替换成功。
双指针方法
代码:
class Solution {
public:
bool canTransform(string start, string end) {
if(start.length() != end.length()) return false;
int i = 0, j = 0;
while(i < start.length() && j < end.length()){
while(i < start.length() && start[i] == 'X') i++;
while(j < end.length() && end[j] == 'X') j++;
if(i == start.length() || j == end.length()) break;
if(start[i] != end[j] || (start[i]=='L' && i < j) || (start[i]=='R' && i > j))
return false;
i++;
j++;
}
while(i<start.length() && start[i]=='X') i++;
while(j<end.length() && end[j]=='X') j++;
return i==start.length() && j==end.length();
}
};
time:O(N), space: O(1).
结果还不错: