




Sponsored
Sponsored
This approach simulates the typing process using two stacks, one for each string. We iterate over each string, using the stack to build the string as it would appear after considering the backspace characters ('#'). By comparing the final stack representations, we can determine if the two strings are equivalent.
Time Complexity: O(n + m), where n and m are the lengths of s and t. Each character is processed once.
Space Complexity: O(n + m) due to the auxiliary arrays used to store the processed results of s and t.
1def backspaceCompare(s: str, t: str) -> bool:
2    def buildFinalString(string: str) -> str:
3        stack = []
4        for ch in string:
5            if ch != '#':
6                stack.append(ch)
7            elif stack:
8                stack.pop()
9        return ''.join(stack)
10    return buildFinalString(s) == buildFinalString(t)
11
12# Example usage:
13print(backspaceCompare("ab#c", "ad#c")) # True
14print(backspaceCompare("ab##", "c#d#")) # True
15print(backspaceCompare("a#c", "b"))   # FalseThis Python solution leverages a list to emulate stack behavior, appending characters unless they're '#', in which case we remove the last element if the list isn't empty. We then compare the two processed strings for equality.
This approach avoids extra space by using two pointers to traverse the strings backwards. By skipping over characters that are effectively backspaced due to a '#' character, we can compare corresponding positions in each string without actually building the resultant strings.
Time Complexity: O(n + m), where n and m are the lengths of s and t.
Space Complexity: O(1), since we only use constant space.
1#include <string>
using namespace std;
bool backspaceCompare(string s, string t) {
    int si = s.length() - 1, ti = t.length() - 1;
    int skipS = 0, skipT = 0;
    while (si >= 0 || ti >= 0) {
        while (si >= 0) {
            if (s[si] == '#') { skipS++; si--; }
            else if (skipS > 0) { skipS--; si--; }
            else break; 
        }
        while (ti >= 0) {
            if (t[ti] == '#') { skipT++; ti--; }
            else if (skipT > 0) { skipT--; ti--; }
            else break;
        }
        if ((si >= 0 && ti >= 0 && s[si] != t[ti]) || ((si >= 0) != (ti >= 0))) {
            return false;
        }
        si--; ti--;
    }
    return true;
}
int main() {
    cout << backspaceCompare("ab#c", "ad#c") << endl; // true
    cout << backspaceCompare("ab##", "c#d#") << endl; // true
    cout << backspaceCompare("a#c", "b") << endl;   // false
    return 0;
}The C++ implementation employs two pointers to iteratively move backwards through the strings, adjusting their position and incrementing or decrementing the backspace counter as needed to simulate the typing effect. We directly compare the characters the pointers land on after properly ignoring the backspaced characters.