20221002 - 777. Swap Adjacent in LR String 在LR字符串中交换相邻字符(双指针)

88 阅读1分钟

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

Solution

题意理解:R 只能往右交换,L 只能往左交换

首先将两个指针 ij 分别指向 startend 的第一个元素。

开始进行循环遍历:

  • 先让两个指针分别指向两个数组的第一个不为 X 的元素
  • 判断这两个元素是否一致,不一致退出 flase
  • 一致就先判断两个指针有没有出界,再看一下相对位置符不符合 R 移动后一定在原来位置右边或原来位置;L 移动后一定在原来位置左边或原来位置,不符合退出 false

最后首尾,没有遍历完的数组如果还有不为 X 的元素,说明前后数组 RL 数量不一致,退出 false

检验完毕没有异常返回 true

bool canTransform(char * start, char * end){
    int i, j, len;
    len = strlen(start);
    i = j = 0;
    while (i < len && j < len) {
        while (start[i] == 'X') i++;
        while (end[j] == 'X') j++;
        if (start[i] != end[j]) return false;
        if (i < len && j < len) {
            char c = start[i];
            if (c == 'R' && i > j || c == 'L' && i < j) return false;
            i++;
            j++;
        }
    }
    while (i < len) {
        if (start[i] != 'X')
            return false;
        i++;
    }
    while (j < len) {
        if (end[j] != 'X')
            return false;
        j++;
    }
    return true;
}

题目链接:777. 在LR字符串中交换相邻字符 - 力扣(LeetCode)