844. Backspace String Compare

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

public class Solution {
    public bool BackspaceCompare(string s, string t) {
        return GetString(s) == GetString(t);
    }
    
    public string GetString(string str) {
        int count = 0;
        var sb = new StringBuilder();
        for(int i = str.Length - 1; i >= 0; i--){
            if(str[i] == '#'){
                count++;
                continue;
            }
            else if(count > 0)
                count--;
            else{
                sb.Append(str[i]);
            }
        }
        return sb.ToString();
    }
}
  • Stack

public class Solution {
    public bool BackspaceCompare(string s, string t) {
        var sStack = new Stack<char>();
        var tStack = new Stack<char>();
        
        foreach(var c in s){
            if(c == '#') sStack.TryPop(out char ch);
            else sStack.Push(c);
        }
        foreach(var c in t){
            if(c == '#') tStack.TryPop(out char ch);
            else tStack.Push(c);
        }
        
        while(sStack.Count > 0 && tStack.Count > 0){
            if(sStack.Pop() != tStack.Pop()) return false;
        }
        
        return sStack.Count == 0 && tStack.Count == 0;
    }
}

Last updated

Was this helpful?