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.
使用栈简单解决,若为([{则进栈,若为)]}则取栈顶,若栈顶为空或不相匹配则返回false;最后栈为空则说明正好匹配完,不为空则有剩余,返回false
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int len=s.length();
int i=0;
while(i<len){
if(s[i]=='('||s[i]=='['||s[i]=='{'){
st.push(s[i]);
}
else{
if(s[i]==')'){
if(st.empty()!=1&&st.top()=='(')
st.pop();
else return false;
}
else if(st.empty()!=1&&s[i]==']'){
if(st.top()=='[')
st.pop();
else return false;
}
else if(st.empty()!=1&&s[i]=='}'){
if(st.top()=='{')
st.pop();
else return false;
}
else return false;
}
i++;
}
if(st.empty())
return true;
else return false;
}
};