题目:Valid Parentheses 有效的括号
20. Valid Parentheses
Easy
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
- 题目解释和基本思路:
这道题目的意思是给我们一个s,string,需要判断这个string是否是有一对对标准的括号组合组成的。题目中向我们解释了合理组合的规则,就是说,假如出现了:
( / { / [ ,那么后面需要出现相对应和括号类型的另一半。在这个思路上我们就很好进行规划了,
- 使用stack作为方法, 存储待处理的符号
- 对括号分成两组,一组为开始的括号组别,一组为结束的括号类型
那么我们来看下code
class Solution(object):
def valid_parentheses(self, s: str) -> bool:
"""
"""
stack = [] # storage the ele that need to handle
opened = ['(', '{', '['] # define the group
closed = [')', '}', ']']
for sub in s:
# sub is from open, put into the stack
# sub is from close:
# case one: is a valid close, pop stack[-1], continue
# case two: is an invalid close, return False
if sub in opened:
stack.append(sub)
else:
if len(stack) > 0 and stack[-1] == opened[closed.index(sub)]:
stack.pop()
else:
return False
return not stack
这里有几个需要注意的地方:
首先, 在对属于closed之中的sub处理的时候。需要是stack之中存在ele的时候,
第二,最后return的判定是为了防止stack之中有还没有处理过得opened sub.