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> 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();
st.pop();
if((s[i] == ']' && c != '[')||(s[i] == '}' && c != '{') || (s[i] == ')' && c != '('))
return false;
}
}
else
st.push(s[i]);
}
return st.empty();
}
};