844. Backspace String Compare

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

/*
    time complexity: O(n), space complexity: O(1)
*/
class Solution {
    public boolean backspaceCompare(String S, String T) {
        // compare each char
        // if encounter #, should count++, int that we know how many word we can passby
        // if after pass by, char is not equal to each other, we should return false
        // all pass means they equal to each other
        
        int s = S.length() - 1;
        int t = T.length() - 1;
        int sCount = 0;
        int tCount = 0;
        
        while (s >= 0 || t >= 0) {
            while (s >= 0 && (sCount > 0 || S.charAt(s) == '#')) {
                if (S.charAt(s) == '#') {
                    sCount++;
                } else {
                    sCount--;
                }
                s--;
            }
            char left = s < 0 ? '@' : S.charAt(s);

            while (t >= 0 && (tCount > 0 || T.charAt(t) == '#')) {
                if (T.charAt(t) == '#') {
                    tCount++;
                } else {
                    tCount--;
                }
                t--;
            }
            char right = t < 0 ? '@' : T.charAt(t);
            
            if (left != right) {
                return false;
            }
            s--;
            t--;
        }
        return true;
    }
}

Last updated