LeetCode 777. Swap Adjacent in LR String 不能互穿 可达性

231 篇文章 0 订阅
120 篇文章 1 订阅

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

 

Constraints:

  • 1 <= len(start) == len(end) <= 10000.
  • Both start and end will only consist of characters in {'L', 'R', 'X'}.

------------------------------------------------

注意审题,只能"XL"->"LX"或者"RX"->"XR",反向是不行的

定义两个指针,从头开始对比,遇到“X”直接跳过,因为根据题意,X可以和R,L交换位置。

不可互穿

1.当两个指针分别遇到第一个非X的字符时,对比,如果不同,不存在移动操作,因为LR是不能互相换位的。

可达性

2.两指针都遇到R字符时,如果start字符串的指针位置比end靠后,不存在,因为移动操作只能使R右移。
3.两指针都遇到L字符时,如果start字符串的指针位置比end靠前,不存在,因为移动操作只能使L左移。

class Solution:
    def canTransform(self, start: str, end: str) -> bool:
        sl = [(v,i) for i,v in enumerate(start) if v != 'X']
        el = [(v,i) for i,v in enumerate(end) if v != 'X']
        if (len(sl) != len(el)):
            return False
        for (s,i),(e,j) in zip(sl,el):
            if (s != e):
                return False
            elif (s == 'L' and j>i):
                return False
            elif (s == 'R' and j<i):
                return False
        return True

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值