#20 Valid Parentheses——Top 100 Liked Questions

谁借莪1个温暖的怀抱¢ 2022-02-02 06:41 294阅读 0赞

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

  1. Input: "()"
  2. Output: true

Example 2:

  1. Input: "()[]{}"
  2. Output: true

Example 3:

  1. Input: "(]"
  2. Output: false

Example 4:

  1. Input: "([)]"
  2. Output: false

Example 5:

  1. Input: "{[]}"
  2. Output: true

“””

第一次:使用栈stack,如果遇到左括号,压入栈中,如果遇到右括号:1)如果stack为空,没有与左括号匹配的右括号,返回false;2)stack不为空,弹出左括号,判断是否与当前右括号匹配,如果匹配,匹遍历下一个括号,不匹配,返回false;3)遍历完成后,看stack中是否有多余的左括号没找到匹配对象,有则返回false

“””

  1. class Solution(object):
  2. def isValid(self, s):
  3. """
  4. :type s: str
  5. :rtype: bool
  6. """
  7. stack = []
  8. for bra in s:
  9. if bra in ['(', '[', '{']:
  10. stack.append(bra)
  11. else:
  12. if len(stack) == 0:
  13. return False
  14. else:
  15. check = stack.pop()
  16. if (check == '(' and bra == ')') or (check == '[' and bra == ']') or (check == '{' and bra == '}'):
  17. continue
  18. else:
  19. return False
  20. return len(stack) == 0

“””

Runtime: 20 ms, faster than 93.77% of Python online submissions for Valid Parentheses.

Memory Usage: 11.9 MB, less than 5.20% of Python online submissions for Valid Parentheses.

“””

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读