LeetCode 777. 在LR字符串中交换相邻字符(C++实现)

LeetCode 777. 在LR字符串中交换相邻字符(C++实现)_第1张图片模拟,以end字符串为基准,当前位置不相等则需要从最靠近当前位置的相等字符往前移,注意可以移动的条件。

class Solution {
public:
    void mySwap(int i, int j, string& str) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    bool canTransform(string start, string end) {
        for (int i = 0; i < end.size(); ++i) {
            if (start[i] == end[i]) {
                continue;
            }
            if (end[i] == 'R' || i == end.size() - 1) {
                return false;
            }

            if (end[i] == 'X') {
                for (int j = i; j < start.size(); ++j) {
                    if (start[j] == 'R' && j != start.size() - 1) {
                        continue;
                    } else if (start[j] == 'X') {
                        mySwap(i, j, start);
                        break;
                    } else {
                        return false;
                    }
                }
            }

            if (end[i] == 'L') {
                for (int j = i; j < start.size(); ++j) {
                    if (start[j] == 'X' && j != start.size() - 1) {
                        continue;
                    } else if (start[j] == 'L') {
                        mySwap(i, j, start);
                        break;
                    } else {
                        return false;
                    }
                }
            }

        }
        return true;
    }
};

你可能感兴趣的:(leetcode,c++,算法)