TreeviewCopyright © aleen42 all right reserved, powered by aleen42
20. 有效的括号
https://leetcode-cn.com/problems/valid-parentheses/
Java
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(char c:s.toCharArray()){
if(c=='('){
stack.push(')');
}else if(c=='['){
stack.push(']');
}else if(c=='{'){
stack.push('}');
}else if(stack.isEmpty()||c!=stack.pop()){
return false;
}
}
return stack.isEmpty();
}
}
Python
'''
@Author: Goog Tech
@Date: 2020-07-16 20:45:17
@Description: https://leetcode-cn.com/problems/valid-parentheses/
@FilePath: \leetcode-googtech\#20. Valid Parentheses\Solution.py
'''
class Solution(object):
def isValid(self, symbolString):
"""
:type s: str
:rtype: bool
"""
index = 0
stack = []
opens = "([{"
closers = ")]}"
balanced = True
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in opens:
stack.append(symbol)
else:
if stack:
top = stack.pop()
if opens.index(top) != closers.index(symbol):
balanced = False
else:
balanced = False
index = index + 1
if stack or not balanced:
return False
else:
return True
print(Solution().isValid("{[()]}"))