题目:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
,
determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are
all valid but "(]"
and "([)]"
are
not.
链接:https://oj.leetcode.com/problems/valid-parentheses/
描述:验证括号序列是不是合法(数据结构教材上的问题。。。)
solution by python:
class Solution:
# @return a boolean
def isValid(self, s):
stk = []
for e in s:
if e=='(' or e=='[' or e=='{':
stk.append(e)
else:
if len(stk) == 0: return False
if e==')':
if stk[-1] != '(': return False
elif e==']':
if stk[-1] != '[': return False
elif e=='}':
if stk[-1] != '{': return False
stk.pop()
return len(stk)==0