2025/3/4 【栈与队列】LeetCode1047. 删除字符串中的所有相邻重复项 【√】

1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)

代码随想录

这题做的没有乐趣

1.使用栈

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        for char in s:
            if stack and stack[-1] == char:
                stack.pop()
            else:
                stack.append(char)
        
        return ''.join(stack)   

 2.用双指针模拟栈。

如果不让用栈可以作为备选方法。

这个方法不错。

class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list(s) 
        n = len(s)
        slow = fast = 0

        while fast < n:
            # 如果一样直接换,不一样会把后面的填在slow的位置
            res[slow] = res[fast]
            # 如果发现和前一个一样,就退一格指针
            if slow > 0 and res[slow] == res[slow-1]:
                slow -= 1
            else:
                slow += 1
            fast += 1
        
        return ''.join(res[:slow])
posted on 2025-03-04 15:13  axuu  阅读(6)  评论(0)    收藏  举报