Swap Adjacent in LR String(交换字符串LR位置)

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'}.

1. 题目大意

给定起始字符串和目标字符串,根据给定的交换规则"XL"——>"LX","RX"——>"XR",判断是否从起始字符串能到达目标字符串。

2.分析

最开始我以为是BFS,题目本身的描述完全满足BFS的条件:(1)有限的状态 (2)明确的目标状态。利用BFS进行求解会出现TTL的问题,主要是中间的状态过多。结合Grandyang的分析,本质上,本题考查的并不是BFS,应该是一种模拟的思路。

根据交换规则,其实就是:相对应target,其实就是"L"往后移动,"R"往前移动,若start字符串能到达target字符串,那么这两个字符串去掉"X"字符后,两者剩下的字符组成的字符串是相等的?主要原因是"L"和"R"两者都是只和"X"交换位置,意味着去掉"X"后两者的字符不相同,说明和"X"交换位置后start状态是无法到达target状态的。例如:"RXLXXR" 和 "LXXRXR",不管如何交换都是无法相同的。

综上:我们可以得到,若start最终经过交换后能到达target状态,则必须满足:start字符串中的"L"在target字符串中的"L"的前面,start字符串中的"R"定会在target字符串中的"R"的后面。根据这必要条件,可以定义两个指针,一个指向start字符串,另外一个指向target字符串;分别遍历到非"X"字符,两者的指针指向的字符进行比较,若不相等,则说明start状态无法到达target;若相等,继续重复上一个步骤,直到遍历完。详见代码:

class Solution {
public:
    bool canTransform(string start, string end) {
        int len = start.size();
        int start_curPos = 0, end_curPos = 0;
        while (start_curPos < len && end_curPos < len) {
            while (start_curPos < len && start[start_curPos] == 'X') ++start_curPos;
            while (end_curPos < len && end[end_curPos] == 'X') ++end_curPos;
            if (start_curPos >= len || end_curPos >= len) break;
            if (start[start_curPos] != end[end_curPos]) return false;
            if (start[start_curPos] == 'L' && start_curPos < end_curPos) return false;
            if (start[start_curPos] == 'R' && start_curPos > end_curPos) return false;
            start_curPos++;
            end_curPos++;
        }

        start = start_curPos == len ? end : start;
        start_curPos = start_curPos == len ? end_curPos : start_curPos;
        while (start_curPos < len) {
            if (start[start_curPos] == 'L' || start[start_curPos] == 'R')
                return false;
            ++start_curPos;
        }
        return true;
    }
};

参考

[1]https://www.cnblogs.com/grandyang/p/9001474.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值