# 844. Backspace String Compare 比较含退格的字符串

@TOC

## # 题目描述

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

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 = "#a#c"
Output: true
Explanation: Both S and T become "c".
``````

Example 4:

``````Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
``````

Note:

1. 1 <= S.length <= 200
2. 1 <= T.length <= 200
3. S and T only contain lowercase letters and '#' characters.

• Can you solve it in O(N) time and O(1) space?

## # 解题方法

### # 字符串切片

``````if s == '#':
if ans_S:
ans_S = ans_S[:-1]
``````

``````if s == '#' and ans_S:
ans_S = ans_S[:-1]
``````

``````class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
ans_S = ""
ans_T = ""
for s in S:
if s == '#':
if ans_S:
ans_S = ans_S[:-1]
else:
ans_S += s
for t in T:
if t == '#':
if ans_T:
ans_T = ans_T[:-1]
else:
ans_T += t
return ans_S == ans_T

``````

### # 栈

``````class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
stackS, stackT = [], []
for s in S:
if s != "#":
stackS.append(s)
elif stackS:
stackS.pop()
for t in T:
if t != "#":
stackT.append(t)
elif stackT:
stackT.pop()
return stackS == stackT
``````

## # 日期

2018 年 6 月 10 日 —— 等了两天的腾讯比赛复赛B的数据集，结果人家在复赛刚开始就给了。。