Given two strings s
and t
, return true
if they are equal when both are typed into empty text editors. '#'
means a backspace character.
Note that after backspacing an empty text, the text will continue to be empty.
Example 1:
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Example 2:
Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".
Example 3:
Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
'#'
character?
'#'
character.s
and t
?
To solve this problem, we need to simulate the typing of the given strings considering the backspace (i.e., '#'
character).
Here’s the strategy we’ll use:
build
which constructs the final string after processing the backspaces.def backspaceCompare(s: str, t: str) -> bool:
def build(string):
result_stack = []
for char in string:
if char != '#':
result_stack.append(char)
elif result_stack:
result_stack.pop()
return ''.join(result_stack)
return build(s) == build(t)
# Test Cases
print(backspaceCompare("ab#c", "ad#c")) # Should print True
print(backspaceCompare("ab##", "c#d#")) # Should print True
print(backspaceCompare("a#c", "b")) # Should print False
build
function iterates through the given string once, processing each character.build
is O(n), where n is the length of the string.build
twice (once for each string), the overall time complexity is O(n + m), where n is the length of s
and m is the length of t
.build(string)
:
'#'
).s
and t
.true
; otherwise, it returns false
.This solution effectively captures the key requirement of handling backspace characters and efficiently compares the resultant strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?