NeetCode #190LC-844EasyTwo Pointers
← Back to All Problems#190 · #844 · Backspace String Compare(比较含退格的字符串)
📌 Problem Statement & Constraints
Given two strings
s and t where # represents a backspace, return whether they are equal after processing all backspaces. A # on an empty text is a no-op. Constraints: 1 <= s.length, t.length <= 200, lowercase letters and #.💡 Core Algorithmic Approaches
- Stack approach: push characters, pop on
#. Compare the two resulting stacks. O(n) time and O(n) space. - Two-pointer approach: walk both strings from the end, skipping characters that are logically deleted by counting
#s, and compare the surviving characters one at a time. - The two-pointer version achieves O(1) extra space, which is the intended follow-up.
- In the two-pointer version,
skipcounts pending backspaces; whileskip > 0, characters are consumed without comparison.
💻 Benchmark Python3 Implementation
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def build(x: str) -> str:
st = []
for ch in x:
if ch == "#":
if st: # '#' on empty text is a no-op
st.pop()
else:
st.append(ch)
return "".join(st)
return build(s) == build(t)
# O(1)-space two-pointer variant
class Solution2:
def backspaceCompare(self, s: str, t: str) -> bool:
i, j = len(s) - 1, len(t) - 1
while True:
skip = 0
while i >= 0 and (skip or s[i] == "#"):
skip += 1 if s[i] == "#" else -1
i -= 1
skip = 0
while j >= 0 and (skip or t[j] == "#"):
skip += 1 if t[j] == "#" else -1
j -= 1
if i < 0 or j < 0:
return i == j # both exhausted
if s[i] != t[j]:
return False
i -= 1
j -= 1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n + m): each character is processed once in both variants.
💾 Space Complexity
O(n + m) for the stack variant; O(1) for the two-pointer variant.
⚠️ Interview Pitfalls & Follow-ups
- Popping from an empty stack:
#on empty text is a no-op, so theif st:guard is required. - Processing the strings forwards in the two-pointer variant: backspaces affect the characters before them, so the scan must go backwards.
- Forgetting the
skipreset between the two strings: each string has its own pending backspace count. - Comparing only when both pointers are valid: the final check must confirm that both strings are exhausted simultaneously.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Two Pointers Problems
中文速览与面试要点
比较含退格的字符串
给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true。 # 代表退格字符。注意:如果对空文本输入退格字符,文本继续为空。进阶:你可以用 O(n) 时间复杂度和 O(1) 空间复杂度解决该问题吗?约束:1 ≤ s.length, t.length ≤ 200;s 和 t 只含有小写字母以及字符 # 。
核心要点
- 栈模拟(直观解) :遍历字符串,遇到普通字符入栈、遇到 # 则弹出栈顶(栈空则忽略)。最后比较两个栈。时间 O(n)、空间 O(n)。
- 双指针从后往前(进阶解,O(1) 空间) :分别用 i、j 从两个字符串末尾往前扫描。维护一个 skip 计数:遇到 # 则 skip += 1 ,遇到普通字符时若 skip > 0 则消耗一个( skip -= 1 )并继续前移。
- 比较逻辑 :两个指针都定位到「下一个有效字符」后进行比较,不同则返回 False;相同时同时前移。
- 终止条件 :两个指针都越界(i < 0 且 j < 0)时返回 True。
常见陷阱
- 栈空时仍执行 pop() :会抛 IndexError。必须先判断 if st 。
- 从前往后扫描却想做到 O(1) 空间 :退格影响的是 前面 已扫描的字符,因此必须从后往前扫描才能用 skip 计数做到 O(1)。
- 双指针版本中 skip 未在每轮重置 :两个字符串各自需要独立的 skip 计数,且每轮开始都要归零。
- 双指针版本中比较时机搞错 :必须先让两个指针都定位到有效字符(跳过所有被退格的字符),再比较。
参考实现
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def build(x: str) -> str:
st = []
for c in x:
if c == '#':
if st:
st.pop() # 空栈时退格无效果
else:
st.append(c)
return ''.join(st)
return build(s) == build(t)
# O(1) 空间的双指针版本(从后往前):
# class Solution:
# def backspaceCompare(self, s: str, t: str) -> bool:
# i, j = len(s) - 1, len(t) - 1
# while True:
# skip = 0
# while i >= 0 and (s[i] == '#' or skip > 0):
# skip += 1 if s[i] == '#' else -1
# i -= 1
# skip = 0
# while j >= 0 and (t[j] == '#' or skip > 0):
# skip += 1 if t[j] == '#' else -1
# j -= 1
# if i < 0 and j < 0:
# return True
# if i < 0 or j < 0 or s[i] != t[j]:
# return False
# i -= 1
# j -= 1