LeetCode20:有效的括号(Valid Parentheses)

小灰灰 2024-04-19 08:03 140阅读 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

中文题目:

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

  1. 输入: "()"
  2. 输出: true

示例 2:

  1. 输入: "()[]{}"
  2. 输出: true

示例 3:

  1. 输入: "(]"
  2. 输出: false

示例 4:

  1. 输入: "([)]"
  2. 输出: false

示例 5:

  1. 输入: "{[]}"
  2. 输出: true

解答:

C++
  1. class Solution:
  2. def isValid(self, s: str) -> bool:
  3. stack = []
  4. lookup = {'(':')','{':'}','[':']'}
  5. for parenthese in s:
  6. if parenthese in lookup:
  7. stack.append(parenthese)
  8. elif len(stack)==0 or lookup[stack.pop()] != parenthese:
  9. return False
  10. return len(stack)==0

发表评论

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

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

相关阅读