更新+补充 1047.删除字符串中的所有相邻重复项.md python代码

补充使用双指针的方法,但是更推荐栈的做法
This commit is contained in:
Eyjan_Huang
2021-08-20 02:55:31 +08:00
committed by GitHub
parent 571defa007
commit ce2c6fb562

View File

@ -197,15 +197,38 @@ class Solution {
Python Python
```python3 ```python3
# 方法一,使用栈,推荐!
class Solution: class Solution:
def removeDuplicates(self, s: str) -> str: def removeDuplicates(self, s: str) -> str:
t = list() res = list()
for i in s: for item in s:
if t and t[-1] == i: if res and res[-1] == item:
t.pop(-1) t.pop()
else: else:
t.append(i) t.append(item)
return "".join(t) # 字符串拼接 return "".join(res) # 字符串拼接
```
```python3
# 双指针
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list(s)
slow = fast = 0
length = len(res)
while fast < length:
# 如果一样直接换不一样会把后面的填在slow的位置
res[slow] = res[fast]
# 如果发现和前一个一样,就退一格指针
if slow > 0 and res[slow] == res[slow - 1]:
slow -= 1
else:
slow += 1
fast += 1
return ''.join(res[0: slow])
``` ```
Go Go