双指针

class Solution {
public:
    bool backspaceCompare(string S, string T) {
        int Ssize = S.size() - 1;
        int Tsize = T.size() - 1;
        int sSkipNum = 0;
        int tSkipNum = 0;
        while (1) {
            while (Ssize >= 0) {
                if (S[Ssize] == '#') {
                    sSkipNum++;
                }
                else {
                    if (sSkipNum > 0) {
                        sSkipNum--;
                    }
                    else {
                        break;
                    }
                }
                Ssize--;
            }
            
             while (Tsize >= 0) {
                if (T[Tsize] == '#') {
                    tSkipNum++;
                }
                else {
                    if (tSkipNum > 0) {
                        tSkipNum--;
                    }
                    else {
                        break;
                    }
                }
                Tsize--;
            }
            
            //后半部分的'#'消耗完成,对比S[Size]和T[Tsize]
            if (Ssize< 0 ||Tsize < 0) {
                break;
            }
            if (S[Ssize] != T[Tsize]) {
                return false;
            }
            Ssize--,Tsize--;
        }
        if(Ssize == -1 && Tsize == -1) {
            return true;
        }
        return false;
    }
};
Last modification:October 19th, 2020 at 11:48 am
如果觉得我的文章对你有用,请随意赞赏