20. Valid Parentheses(括号匹配,用桟)
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.
class Solution { public: bool isValid(string s) { stack<char> stk; for (char c : s) { if (c == '(' || c == '[' || c=='{') { stk.push(c); } else if (!stk.empty() && leftof(c)==stk.top()) { stk.pop(); } else { return false; } } return stk.empty(); } char leftof(char c) { if (c == ')') return '('; if (c == '}') return '{'; if (c == ']') return '['; return c; } };
1 class Solution: 2 def isValid(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 stack = [] 8 d={'(':')','[':']','{':'}'} 9 for i in s: 10 if i in d.keys():#遇到左括号 压桟 11 stack.append(i) 12 else: #遇到右括号 13 if stack ==[]: #桟为空,没有匹配的 14 return False 15 else: 16 if i==d[stack[-1]] : #如果匹配上,弹桟 17 stack.pop() 18 else: 19 return False #没有匹配上 20 return stack==[] #如果遍历完之后桟为空,则全部匹配 21 22 23