#方法一:使用栈
# class Solution:
# def removeDuplicates(self, s):
# res = []
# for char in s:
# #真和消消乐一样,栈外来一个数据,如果和栈顶数据相同,则不仅不入栈,还把栈顶数据消掉了
# if res and res[-1] == char:
# res.pop()
# else:
# res.append(char)
# return "".join(res) # 字符串拼接
#方法二:使用双指针模拟栈,如果不让用栈可以作为备选方法。
# class Solution:
# def removeDuplicates(self, s):
# #要把字符串转换成列表进行操作
# 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
# #下面的res要加上[0:slow],因为既有slow,又有fast,不能省略着写了
# return ''.join(res[0: slow])
class Solution:
def removeDuplicates(self,s):
res=list(s)
slow=fast=0
while fast<len(s):
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])