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

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

被折叠的 条评论
为什么被折叠?



