【Leetcode】777. Swap Adjacent in LR String在LR字符串中交换相邻字符

在一个由 ‘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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值