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

Backspace String Compare #132

Open
jzhangnu opened this issue Aug 7, 2018 · 0 comments
Open

Backspace String Compare #132

jzhangnu opened this issue Aug 7, 2018 · 0 comments

Comments

@jzhangnu
Copy link
Owner

jzhangnu commented Aug 7, 2018

var backspaceCompare = function(S, T) {
    let t1 = '', t2 = '';

    for (let i = 0; i < S.length; i++) {
        let s = S.charAt(i);
        s !== '#' ? t1 += s : t1 = t1.slice(0, t1.length-1);
    }

    for (let i = 0; i < T.length; i++) {
        let t = T.charAt(i);
        t !== '#' ? t2 += t : t2 = t2.slice(0, t2.length-1);
    }

    return t1 === t2;
}



var backspaceCompare = function(S, T) {
    var i = S.length-1, j = T.length-1,
        sk1 = 0, sk2 = 0;

    while (i >= 0 || j >= 0) {
        while (i >= 0) {
            if (S.charAt(i) === '#') {
                sk1++;
                i--;
            }
            else if (sk1 > 0) {
                sk1--;
                i--;
            }
            else break;
        }
        while (j >= 0) {
            if (T.charAt(j) === '#') {
                sk2++;
                j--;
            }
            else if (sk2 > 0) {
                sk2--;
                j--;
            }
            else break
        }

        if(i >=0  && j >= 0 && S.charAt(i) != T.charAt(j)) return false;
        
        if ((i >= 0) ^ (j >= 0)) 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