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 <= len(start) = len(end) <= 10000
.- Both start and end will only consist of characters in
{'L', 'R', 'X'}
.
思路:先观察规律,无非就是L可以往左边移动,R可以往右边移动
这样的话XXXL就可以移动成XXLX,XLXX,LXXX,那就想到一个个character比,如果前面一直都是L,X,这时在i位置出现一个R,那么可以明确的是,i位置前面的start和end要能匹配,因为L,X都不能从左边穿过R
R,X组合也是一样的道理
唯一需要注意的一点是start的L当前count总数不能大于end的Lcount总数,因为L不能往最右边移动,R也是同理
import re
class Solution:
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
r1=r2=l1=l2=x1=x2=i=0
while i<len(start):
if (r1!=0 and start[i]=='L') or (l1!=0 and start[i]=='R') or (r2!=0 and end[i]=='L') or (l2!=0 and end[i]=='R'):
if r1!=r2 or l1!=l2 or x1!=x2: return False
r1=r2=l1=l2=x1=x2=0
if start[i]=='L': l1+=1
elif start[i]=='R':r1+=1
else: x1+=1
if end[i]=='L': l2+=1
elif end[i]=='R':r2+=1
else: x2+=1
if l1>l2 or r1<r2: return False
i += 1
return r1==r2 and l1==l2 and x1==x2
#print(re.sub(r'(X)\1+', 'X', 'RXXLRXRXL'))
s=Solution()
#print(s.canTransform('R', 'L'))
#print(s.canTransform('RXXLRXRXL', 'XRLXXRRLX'))
#print(s.canTransform('XXXXXLXXXX', 'LXXXXXXXXX'))
print(s.canTransform('XXRXXLXXXX', 'XXXXRXXLXX'))