mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
更新+补充 1047.删除字符串中的所有相邻重复项.md python代码
补充使用双指针的方法,但是更推荐栈的做法
This commit is contained in:
@ -197,15 +197,38 @@ class Solution {
|
||||
|
||||
Python:
|
||||
```python3
|
||||
# 方法一,使用栈,推荐!
|
||||
class Solution:
|
||||
def removeDuplicates(self, s: str) -> str:
|
||||
t = list()
|
||||
for i in s:
|
||||
if t and t[-1] == i:
|
||||
t.pop(-1)
|
||||
res = list()
|
||||
for item in s:
|
||||
if res and res[-1] == item:
|
||||
t.pop()
|
||||
else:
|
||||
t.append(i)
|
||||
return "".join(t) # 字符串拼接
|
||||
t.append(item)
|
||||
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:
|
||||
|
Reference in New Issue
Block a user