LeetCode每日一题- day8
新手入坑LeetCode,每天打卡一道题
算法不一定很好,只是我自己的一个水平体现,做个自己刷题的记录,欢迎交流学习
(尽量AC LeetCode官方的每日一题)
欢迎交流学习!
题目:777. 在LR字符串中交换相邻字符
在一个由 ‘L’ , ‘R’ 和 ‘X’ 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换一个"XL",或者用一个"XR"替换一个"RX"。现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动操作使得start可以转换成end时, 返回True。
思路:
替换操作实际上是将 L
往左移动(L
左边为X
时才能移动),R
往右移动(R
右边是 X
时才能移动),但 L
无法穿过 R
,R
也无法穿过L
。所以,如果去掉 start
和 end
中的所有 X
,剩下的字符应该是相同的,否则返回 false
。
我们使用双指针 i
和 j
从头到尾遍历 start
和 end
:
如果当前字符为 L
且 i<j
,那么这个 L
无法向右移动,返回 false
;如果当前字符为 R
且 i>j
,那么这个 R
无法向左移动,返回 false
。
如果双指针均遍历到末尾,返回 true
。
代码:
class Solution:
def canTransform(self, start: str, end: str) -> bool:
n = len(start)
i = j = 0
while 1:
while i < n and start[i] == 'X':
i += 1
while j < n and end[j] == 'X':
j += 1
if i >= n and j >= n:
return True
if i >= n or j >= n or start[i] != end[j]:
return False
if start[i] == 'L' and i < j:
return False
if start[i] == 'R' and i > j:
return False
i, j = i + 1, j + 1