美文网首页LeetCode
1047. 删除字符串中的所有相邻重复项

1047. 删除字符串中的所有相邻重复项

作者: MarcQAQ | 来源:发表于2021-03-09 06:06 被阅读0次

    给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它> > 们。
    在 S 上反复执行重复项删除操作,直到无法继续删除。
    在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
    输入:"abbaca"
    输出:"ca"
    解释:例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删> 除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,> > 所以最后的字符串为 "ca"。

    可以用栈解决。扫描一遍字符串,当栈为空或者当前字符和栈顶字符不一样的时候入栈,否则出栈。扫描结束后,从底到顶输出栈内剩余的元素就是答案。容易得知,时间空间复杂度均为O(n)

    class Solution:
        def removeDuplicates(self, S: str) -> str:
            stack = list()
            for ch in S:
                if len(stack) == 0 or ch != stack[-1]:
                    # if stack is empty or current char
                    # not the same as the one on top of
                    # stack, just push it into the stack
                    stack.append(ch)
                else:
                    # otherwise, pop from stack and ignore
                    # current char
                    stack.pop()
    
            return ''.join(stack)
    

    相关文章

      网友评论

        本文标题:1047. 删除字符串中的所有相邻重复项

        本文链接:https://www.haomeiwen.com/subject/iflvqltx.html