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 ce2c6fb

Browse files
更新+补充 1047.删除字符串中的所有相邻重复项.md python代码
补充使用双指针的方法,但是更推荐栈的做法
1 parent 571defa commit ce2c6fb

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

‎problems/1047.删除字符串中的所有相邻重复项.md‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -197,15 +197,38 @@ class Solution {
197197

198198
Python:
199199
```python3
200+
# 方法一,使用栈,推荐!
200201
class Solution:
201202
def removeDuplicates(self, s: str) -> str:
202-
t = list()
203-
for i in s:
204-
if t and t[-1] == i:
205-
t.pop(-1)
203+
res = list()
204+
for item in s:
205+
if res and res[-1] == item:
206+
t.pop()
206207
else:
207-
t.append(i)
208-
return "".join(t) # 字符串拼接
208+
t.append(item)
209+
return "".join(res) # 字符串拼接
210+
```
211+
212+
```python3
213+
# 双指针
214+
class Solution:
215+
def removeDuplicates(self, s: str) -> str:
216+
res = list(s)
217+
slow = fast = 0
218+
length = len(res)
219+
220+
while fast < length:
221+
# 如果一样直接换,不一样会把后面的填在slow的位置
222+
res[slow] = res[fast]
223+
224+
# 如果发现和前一个一样,就退一格指针
225+
if slow > 0 and res[slow] == res[slow - 1]:
226+
slow -= 1
227+
else:
228+
slow += 1
229+
fast += 1
230+
231+
return ''.join(res[0: slow])
209232
```
210233

211234
Go:

0 commit comments

Comments
(0)

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