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

比较含退格的字符串 #239

Open
louzhedong opened this issue Apr 17, 2021 · 0 comments
Open

比较含退格的字符串 #239

louzhedong opened this issue Apr 17, 2021 · 0 comments

Comments

@louzhedong
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 只含有小写字母以及字符 '#'。

进阶:

你可以用 O(N) 的时间复杂度和 O(1) 的空间复杂度解决该问题吗?

思路

普通思路:用栈来计算出处理过后的字符串,进行对比

进阶思路:由于#会退回前面的字符串,所以我们可以从后面进行遍历,采用双指针的方法

解答

栈解法

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var backspaceCompare = function(s, t) {
    var sStack = [], tStack = [];
    for (var i = 0; i < s.length; i ++) {
        if (s[i] == '#') {
            sStack.pop();
        } else {
            sStack.push(s[i]);
        }
    }
    for (var j = 0; j < t.length; j++) {
        if (t[j] == '#') {
            tStack.pop();
        } else {
            tStack.push(t[j]);
        }
    }

    return sStack.join('') == tStack.join('');
};

双指针解法

var backspaceCompare = function(S, T) {
    let i = S.length - 1,
        j = T.length - 1,
        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(S[i] !== T[j]) return false;
        i--;
        j--;
    }
    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