Problem Description:
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.
题目要求判断输入字符串是否有效,有效的标准是所有的括号必须正确的顺序闭合。
思路一:
用python的List实现栈,用栈的数据结构处理给定字符串。将当前位置的字符入栈,当栈顶的括号和正要入栈的字符括号匹配时将栈顶的括号弹出,不然将新的括号压入栈中。当全部元素入栈后,只有当栈里没有括号时,此时给定的字符串是有效的。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = [None]
map = {')':'(', ']':'[', '}':'{'}
for c in s:
if c in map and map[c] == stack[-1]:
stack.pop()
else:
stack.append(c)
if len(stack) == 1:
return True
else:
return False
结果如下:
优化一下:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = [None]
map = {')':'(', ']':'[', '}':'{'}
for c in s:
if c in map:
if map[c] != stack[-1]:
return False
stack.pop()
else:
stack.append(c)
if len(stack) == 1:
return True
else:
return False
结果如下:
Python中栈的知识点:
堆栈 (Stack) 是限制在表的一端进行插入和删除运算的线性表,通常称插入、删除的这一端为栈顶(Top),另一端为栈底 (Bottom) 。先进后出(FILO)。
在python中,栈可以用列表来代替。其中入栈利用append函数,出栈利用pop函数。