## 题目描述：

LeetCode 777. Swap Adjacent in LR String

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. `1 <= len(start) = len(end) <= 10000`.
2. Both start and end will only consist of characters in `{'L', 'R', 'X'}`.

## 解题思路：

```从左向右遍历start和end，在遍历过程中，start中的字符R的个数应当不小于end中字符R的个数（保证R没有发生相对左移）

## Python代码：

``````class Solution(object):
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
N = len(start)
sR = eR = sL = eL = 0
for x in range(N):
if start[x] == 'R': sR += 1
if end[x] == 'R': eR += 1
if sR < eR: return False
if sR != eR: return False

for x in range(N - 1, -1, -1):
if start[x] == 'L': sL += 1
if end[x] == 'L': eL += 1
if sL < eL: return False
if sL != eL: return False

start, end = start.replace('X', ''), end.replace('X', '')
return start.split('R') == end.split('R')
``````

Pingbacks已关闭。