Leetcode 2390. Removing Stars From a String

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 2390. Removing Stars From a String_第1张图片

2. Solution

**解析:**Version 1,使用数据结构栈,可以解决这个问题,时间复杂度O(N)。字符每次入栈之前判断是否是星号,如果是,则栈顶元素出栈,继续下一个字符,否则入栈。

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

Reference

  1. https://leetcode.com/problems/removing-stars-from-a-string/

你可能感兴趣的:(Leetcode,leetcode,算法,职场和发展)