LeetCode_844-Backspace String Compare

输入两个字符串S和T,字符串只包含小写字母和”#“,#表示为退格键,判断操作完退格键剩下字符串是否相等
例子:
S = “ab#c", T = "ad # c” 返回true,剩下的字符串是”ac“
S = “ab##", T = "c # d # ” 返回true,剩下的字符串是”“

class Solution {
public:
    bool backspaceCompare(string S, string T) {
        stack<char> stackS;
        stack<char> stackT;
        for(int i=0; i<S.length(); i++) {
            if(S[i] == '#' && !stackS.empty()) {
                stackS.pop();
            }
            else if(S[i] != '#'){
                stackS.push(S[i]);
            }
        }
        for(int i=0; i<T.length(); i++) {
            if(T[i] != '#' && !stackT.empty()) {
                stackT.pop();
            }
            else if(T[i] != '#') {
                stackT.push(T[i]);
            }
        }
       
        return (stackS == stackT);
    }
};

可关注公众号了解更多的面试技巧

猜你喜欢

转载自www.cnblogs.com/yew0/p/11613924.html