力扣 在LR字符串中交换相邻字符(双指针)

题目:传送门

思路:记录’X‘值之外字符的坐标(或者双指针)

代码:
c++(记录坐标)

class Solution {
public:
    vector v, v1;
    bool canTransform(string s, string e) {
        for(int i = 0; i < s.length(); i++) {
            if(s[i] == 'X')continue;
            v.push_back(node(i, s[i]));
        }
        for(int i = 0; i < e.length(); i++) {
            if(e[i] == 'X')continue;
            v1.push_back(node(i, e[i]));
        }
        if(v1.size() != v.size())return false;
        for(int i = 0; i  v[i].p) {
                return false;
            }
        }
        return true;
    }
};

python(双指针)

class Solution:
    def canTransform(self, s: str, e: str) -> bool:
        i = 0
        j = 0
        n = len(s)
        while i < n and j < n:
            while i < n and s[i] == 'X':
                i += 1
            while j < n and e[j] == 'X':
                j += 1
            if i >= n or j >= n:
                continue
            if s[i] == e[j]:
                if s[i] == 'L' and i < j:
                    return False
                if s[i] == 'R' and i > j:
                    return False
            else:
                return False
            i += 1
            j += 1
        while i < n and s[i] == 'X':
            i += 1
        while j < n and e[j] == 'X':
            j += 1  
        if i < n or j < n:
            return False
        return True

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