前言:这道题目在《数据结构》这本书上有讲,学习真的很重要啊!
题目:
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) {
if(s=="")
return false;
stack<char> st;
for(int i=0;i!=s.length();i++){
if(s[i]==')'||s[i]=='}'||s[i]==']'){
if(st.empty()){
return false;
}
else{
char c=st.top();
if(c=='('&&s[i]!=')'||c=='{'&&s[i]!='}'||c=='['&&s[i]!=']'){
return false;
}
else{
st.pop();
}
}
}
else{
st.push(s[i]);
}
}
return (st.empty())?true:false;
}
};