![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8d116b5db26c1435ac23a121b1fd20a7.png)
class Solution(object):
def backspaceCompare(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# 1.用栈清除元素后比较
def fun(str_):
result = list()
for i in str_:
if i != '#':
result.append(i)
elif result:
result.pop()
return "".join(result)
return fun(s) == fun(t)
class Solution(object):
def backspaceCompare(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# 2.双指针法
# 因为#会去掉前面的字符,使用两个指针从后往前遍历,对比,不相等就返回false
i, j = len(s)-1, len(t)-1
# skipS, skipT是用来记录#的
skipS, skipT = 0, 0
while i >= 0 or j >= 0:
# 循环字符串s
while i >= 0:
if s[i] == '#':
skipS += 1
i -= 1
elif skipS:
skipS -= 1
i -= 1
else:
break
# 循环字符串t
while j >= 0:
if t[j] == '#':
skipT += 1
j -= 1
elif skipT:
skipT -= 1
j -= 1
else:
break
if i>=0 and j>=0:
if s[i] != t[j]:
return False
elif i>=0 or j>=0:
return False
i -= 1
j -= 1
return True