在一个由 ‘L’ , ‘R’ 和 ‘X’ 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换一个"XL",或者用一个"XR"替换一个"RX"。现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动操作使得start可以转换成end时, 返回True。
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’}.
Hints:
Think of the L and R’s as people on a horizontal line, where X is a space. The people can’t cross each other, and also you can’t go from XRX to RXX.
【题意】
从题目和例子及暗示可以看出,本题的意思是L 可以像左移动,R可以像右移动,却不能跨过X。
那我们把start 和 end字符中的X字符全部剔除,则得到的新的两个字符串一定相等。
除此之外,L 左移动 ===》start 字符串里的L相对于end来说偏右,即start 字符里出现的L 一定在end字符串相同位置及之前出现。同理 start里的出现R一定比end字符串出现的早。
class Solution {
public:
bool canTransform(string start, string end) {
string s,t;
for(auto st:start)
{
if(st != 'X')
s += st;
}
for(auto en:end)
{
if(en != 'X')
t += en;
}
if(s != t) return false; //判断剔除X之后 两个字符串是否相等。
int sl = 0, sr = 0, el = 0, er = 0;
for( int i = 0 ; i < end.size(); i++)
{
if(start[i] == 'L') sl ++;
if(start[i] == 'R') sr ++;
if(end[i] == 'L') el ++;
if(end[i] == 'R') er ++;
if(sl > el || sr < er) return false; //start,end 里的出现L,R快慢。
return true;
}
};