844. 比较含退格的字符串

4/15/2021 Leetcode

# 题目

https://leetcode-cn.com/problems/backspace-string-compare/

# 思路

用栈处理遍历过程,每次我们遍历到一个字符:

  • 如果它是退格符#,那么我们将栈顶字符弹出;
  • 如果它是普通字符,那么我们将其压入栈中。

# 代码

class Solution {
public:
    string Build(string str){
            string s;
            for(char t:str){
                if(t!='#'){
                    s.push_back(t);
                }else if(!s.empty()){
                    s.pop_back();
                }
            }
            return s;
        }
    bool backspaceCompare(string S, string T) {
        return Build(S)==Build(T);
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17