1 Description(描述)
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.
以下两种情况是有效的:
1.开括号必须由相同类型的括号关闭。
2.开括号必须按正确顺序关闭。
Note that an empty string is also considered valid.
注意,空字符串也被认为是有效的。
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
2 Solution(解决方案)
很好的思想就是哈希表存储括号信息,利用栈来做运算,逐个读取输入的字符,如果遇到右括号,则取栈顶元素并判断是否是与该右括号匹配的左括号,如果不是则返回false,如果遇到左括号,则入栈。最后判断栈是否为空,如果为空则匹配成功返回true,不为空则返回false。
def isValid(s):stack = []mapping = {")": "(", "}": "{", "]": "["}for char in s:if char in mapping:top_element = stack.pop() if stack else '#'if mapping[char] != top_element:return Falseelse:stack.append(char)return not stack