https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/
class Solution:
def removeDuplicates(self, s: str) -> str:
stack =[]
for item in s:
if not stack:
stack.append(item)
continue
if item==stack[-1]:
stack.pop()
else :
stack.append(item)
str_new= ''.join (stack)
return str_new
# 方法二,使用栈
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list()
for item in s:
# 这个用了更加简洁的方式,是把空或不相等的情况都用else来处理,我们第一个方法,是分别走第一个if判断空,else判断 不相等
if res and res[-1] == item:
res.pop()
else:
res.append(item)
return "".join(res) # 字符串拼接
方法三的双指针需要在思考下
# 方法三,使用双指针模拟栈,如果不让用栈可以作为备选方法。
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])
LeetCode:删除字符串相邻重复项
439

被折叠的 条评论
为什么被折叠?



