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 1:

Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: true
Explanation: We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

Example 2:

Input: start = "X", end = "L"
Output: false

Constraints:

  • 1 <= start.length <= 104
  • start.length == end.length
  • Both start and end will only consist of characters in 'L''R', and 'X'.

题目:一串开始字符串包含L,R,和X。可以将“XL”替换为“LX”, 也可以将“RX”替换为“XR”。给定一个结束字符串,问可否通过替换操作将开始字符串转变为结束字符串。

思路:注意,题中有坑。很容易理解为“XL”和“LX”可以互相替换,“XR”和“RX”可以互相替换。其实不是的,替换是单项的,小编第一次做就理解成双向替换了T_T。再看一遍发现L字符只可以往左走,R字符只能往右走,理解到这里那就好办了。有几种情况会返回false:

        1,字符串长度不相等,怎么替换也不行

        2,字符串L,R,X的个数不相等,怎么替换也不行

        3,字符串L, R的相对位置不一致,即去除X后两个字符串不相等。

        4,end字符串中对应的L字符靠右或者对应的R字符靠左,都不可能替换成功。

双指针方法

代码:

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

time:O(N), space: O(1).

结果还不错:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值