当前位置:网站首页>2022-7-7 Leetcode 844. Compare strings with backspace

2022-7-7 Leetcode 844. Compare strings with backspace

2022-07-07 13:39:00 weixin_ fifty-one million one hundred and eighty-seven thousand

 Insert picture description here
 Insert picture description here
Method 1 : Stack


class Solution {
    
public:
    bool backspaceCompare(string s, string t) {
    
        string tmps = "", tmpt = "";
        for (auto& ch:s){
    
            if (ch == '#'){
    
                if (!tmps.empty())
                tmps.pop_back();
            }else tmps.push_back(ch);
        }

        for (auto& ch:t){
    
            if (ch == '#'){
    
                if (!tmpt.empty())
                tmpt.pop_back();
            }else tmpt.push_back(ch);
        }
        return tmps == tmpt;
    }
};

Method 2 : Double pointer

class Solution {
    
public:
    bool backspaceCompare(string S, string T) {
    
        int i = S.length() - 1, j = T.length() - 1;
        int skipS = 0, skipT = 0;

        while (i >= 0 || j >= 0) {
    
            while (i >= 0) {
    
                if (S[i] == '#') {
    
                    skipS++, i--;
                } else if (skipS > 0) {
    
                    skipS--, i--;
                } else {
    
                    break;
                }
            }
            while (j >= 0) {
    
                if (T[j] == '#') {
    
                    skipT++, j--;
                } else if (skipT > 0) {
    
                    skipT--, j--;
                } else {
    
                    break;
                }
            }
            if (i >= 0 && j >= 0) {
    
                if (S[i] != T[j]) {
    
                    return false;
                }
            } else {
    
                if (i >= 0 || j >= 0) {
    
                    return false;
                }
            }
            i--, j--;
        }
        return true;
    }
};

 author :demigodliu
 link :https://leetcode.cn/problems/backspace-string-compare/solution/shuang-zhi-zhen-bi-jiao-han-tui-ge-de-zi-8fn8/
 source : Power button (LeetCode)
 The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
原网站

版权声明
本文为[weixin_ fifty-one million one hundred and eighty-seven thousand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071136083233.html