题意描述: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.
分析:栈
AC代码:
bool isValid(string s) {
vector<char> stack;
for(int i = 0; i < s.size(); ++i){
if(s[i] == '}' || s[i] == ']' || s[i] == ')'){
if(!stack.empty()){
if(s[i] == '}' && stack.back() == '{' || s[i] == ']' && stack.back() == '[' || s[i] == ')' && stack.back() == '(')
stack.pop_back();
else
return false;
}else{
return false;
}
}else{
stack.push_back(s[i]);
}
}
if(stack.empty()){
return true;
}else{
return false;
}
}