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

本文探讨了一种特殊的字符串转换问题,即通过有限的操作将一个由'L'、'R'和'X'组成的字符串转换为另一个字符串。文章详细解释了转换规则,并提供了一个算法解决方案,用于判断两个字符串是否可以通过这些操作相互转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值