[LeetCode 777] Swap Adjacent in LR String

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. 1 <= len(start) = len(end) <= 10000.
  2. 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的位置。

举例说明:

startXLXRRXXRXX
endLXXXXXXRRR
s1 1        
e10         
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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值