Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 064ce8f

Browse files
committed
Update array.md
比较含退格的字符串
1 parent e35c827 commit 064ce8f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎data_structure/array.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,56 @@ class Solution:
149149

150150
```
151151

152+
### [比较含退格的字符串](https://leetcode.cn/problems/backspace-string-compare/)
153+
> 给定 s 和 t 两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true 。# 代表退格字符。注意:如果对空文本输入退格字符,文本继续为空。
154+
155+
思路:两种方法,直接堆栈和双指针
156+
157+
**Python版本一**
158+
```python
159+
class Solution:
160+
def backspaceCompare(self, s: str, t: str) -> bool:
161+
s_b = backspace(s)
162+
t_b = backspace(t)
163+
return s_b == t_b
164+
165+
def backspace(s):
166+
s_b = list()
167+
i = 0
168+
while i < len(s):
169+
if s[i] != '#': s_b.append(s[i])
170+
else:
171+
if len(s_b): s_b.pop()
172+
i = i + 1
173+
return ''.join(s_b)
174+
175+
```
176+
177+
**Python版本二**
178+
```python
179+
class Solution:
180+
def backspaceCompare(self, s: str, t: str) -> bool:
181+
## 倒着遍历
182+
sr, tr = len(s) - 1, len(t) - 1
183+
while sr >= 0 or tr >= 0:
184+
skip = 0
185+
while skip >= 0 and sr >= 0:
186+
if s[sr] != '#': skip -= 1
187+
else: skip += 1
188+
sr -= 1
189+
st = s[sr+1] if skip < 0 else ''
190+
191+
skip = 0
192+
while skip >= 0 and tr >= 0:
193+
if t[tr] != '#': skip -= 1
194+
else: skip += 1
195+
tr -= 1
196+
tt = t[tr+1] if skip < 0 else ''
197+
198+
if st != tt: return False
199+
return True
200+
```
201+
152202

153203
### [spiral-matrix](https://leetcode-cn.com/problems/spiral-matrix/)
154204

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /