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> a;
for(char& n:s) {
switch(n) {
case'(':
case'{':
case'[': a.push(n); break;
case')': if(a.empty() || a.top()!='(') return false; else a.pop(); break;
case'}': if(a.empty() || a.top()!='{') return false; else a.pop(); break;
case']': if(a.empty() || a.top()!='[') return false; else a.pop(); break;
default:;
}
}
return a.empty()?true:false;
}
};