题目内容
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
https://leetcode-cn.com/problems/valid-parentheses/
Given a string 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.
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
题目思路
这就是一道典型的栈的应用题目。建立一个栈,如果是左括号就入栈,如果是右括号的话,先判断是否空栈,然后再匹配。最后如果读取全部的字符后,栈也是空的。则正确。
程序代码
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
stack=[]
for i in range(len(s)):
if s[i]=='(' or s[i]=='[' or s[i]=='{':
stack.append(s[i])
elif s[i]==')':
if not stack:
return False
if stack[-1]=='(':
stack.pop()
else:
return False
elif s[i]==']':
if not stack:
return False
if stack[-1]=='[':
stack.pop()
else:
return False
elif s[i]=='}':
if not stack:
return False
if stack[-1]=='{':
stack.pop()
else:
return False
if not stack:
return True
else:
return False