• 字符串为空且仅包含小写字符,或

  • 字符串可以写成AB(A与B连接),其中A和B是有效字符串,或

  • 字符串可以写成(A)的形式,其中A是有效字符串。

  • 因此,如果输入类似于s="m)n(o)p",那么输出将是"mn(o)p"

    示例

    让我们看看以下实现以获得更好的理解-

    def solve(s):
       stack = []
       indexes = set()
       i = 0
    
       for c in s:
          if c == '(':
             stack.append(i)
          elif c == ')':
             if len(stack) == 0:
                indexes.add(i)
             else:
                stack.pop()
          i += 1
    
       ret = ''
       indexes = indexes.union(stack)
       for i in range(len(s)):
          if i not in indexes:
             ret += s[i]
    
       return ret
    
    s = "m)n(o)p"
    print(solve(s))

    输入

    "m)n(o)p"
    输出结果
    mn(o)p

    热门推荐