Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 844. 比较含退格的字符串 #52

Open
Animenzzzz opened this issue Aug 15, 2019 · 0 comments
Open

[LeetCode] 844. 比较含退格的字符串 #52

Animenzzzz opened this issue Aug 15, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。

示例 1:

输入:S = "ab#c", T = "ad#c"
输出:true
解释:S 和 T 都会变成 “ac”。
示例 2:

输入:S = "ab##", T = "c#d#"
输出:true
解释:S 和 T 都会变成 “”。

示例 3:

输入:S = "a##c", T = "#a#c"
输出:true
解释:S 和 T 都会变成 “c”。

示例 4:

输入:S = "a#c", T = "b"
输出:false
解释:S 会变成 “c”,但 T 仍然是 “b”。

提示:

1 <= S.length <= 200
1 <= T.length <= 200
S 和 T 只含有小写字母以及字符 '#'。

解题思路:比较简单,使用两个栈,遇到#就出栈。最后比较两个栈是否相等

C++解法:

class Solution {
public:
    bool backspaceCompare(string S, string T) {
        stack<char> ss,tt;
        for (int i = 0; i < S.size(); i++)
        {
            if(S[i] == '#'){
                if(!ss.empty()) ss.pop();
                continue;
            }
            ss.push(S[i]);
        }
        for (int i = 0; i < T.size(); i++)
        {
            if(T[i] == '#'){
                if(!tt.empty()) tt.pop();
                continue;
            }
            tt.push(T[i]);
        }
        if(ss.size() != tt.size()) return false;
        while (!ss.empty())
        {
            if(ss.top() != tt.top()) return false;
            ss.pop();tt.pop();
        }
        return true;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant