20. 有效的括号

Easy

思路

使用求解,想象一下我们在玩消消乐游戏。

以上,AC!

代码

python3

class Solution:
  def isValid(self, s: str) -> bool:
    stack = []
    pairs = {'{':'}','(':')','[':']'}
    for l in s:
    if len(stack) == 0:
        stack.append(l)
        continue
    pre = stack[-1]
    if pre in pairs and pairs[pre] == l:
        stack.pop()
    else:
        stack.append(l)
    return len(stack) == 0