20 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
【解题C++】
很经典的一道题啦~不多说,都在注释里。
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.length();i++)
{
//如果栈为空,直接入栈
if(st.empty())
st.push(s[i]);
//如果栈中有符号,将它和准备入栈的符号进行对比,匹配的话,栈中符号出栈
else if((st.top()=='('&&s[i]==')')||(st.top()=='['&&s[i]==']')||(st.top()=='{'&&s[i]=='}'))
st.pop();
//否则,继续入栈
else
st.push(s[i]);
}
//最后如果栈为空,说明匹配成功
return st.empty();
}
};
【解题Python】
自己开头写了一个巨垃圾的代码,看完官方题解默默删掉重来= = 思路是一样的,但是Python可以写得更灵活一些,看来我应该多熟悉一下Python的语法了。
class Solution:
def isValid(self, s: str) -> bool:
# 字典大法好!!!注意这里是右边符号:左边符号
mapping = {')':'(',']':'[','}':'{'}
# 用列表模拟栈
stack = []
for str in s:
# 如果当前字符为右边括号
if str in mapping:
# 如果栈不为空,弹出栈顶元素并赋值给top,不然赋个无效值
top = stack.pop() if stack else '#'
# 如果栈顶元素不是匹配的左括号,返回错误
if mapping[str] != top:
return False
# 如果当前字符为左边括号,入栈
else:
stack.append(str)
# 栈为空,返回正确
return not stack