[leetcode] 777. Swap Adjacent in LR String

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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’}.

分析

题目的意思是:给定start串和end串,L表示可以向左移,R可以向右移动,L和R只能根X交换位置,问start可不可以通过移动变成end串。

  • 不论是L还是R,其只能跟X交换位置,L和R之间是不能改变相对顺序的,所以如果分别将start和end中所有的X去掉后的字符串不相等的话,那么就永远无法让start和end相等了。

  • 这个判断完之后,就来验证L只能前移,R只能后移这个限制条件吧,当i指向start中的L时,那么j指向end中的L必须要在前面,所以如果i小于j的话,就不对了,同理,当i指向start中的R,那么j指向end中的R必须在后面,所以i大于j就是错的,最后别忘了i和j同时要自增1,不然死循环了。

代码

class Solution {
public:
    bool canTransform(string start, string end) {
        int i=0,j=0;
        int n=start.size();
        while(i<n&&j<n){
            while(i<n&&start[i]=='X') ++i;
            while(j<n&&end[j]=='X') ++j;
            if(start[i]!=end[j]) return false;
            if((i<j&&start[i]=='L')||(i>j&&start[i]=='R')){
                return false;
            }
            i++;
            j++;
        }
        return true;
    }
};

参考文献

[LeetCode] Swap Adjacent in LR String 交换LR字符串中的相邻项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值