题目
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<int> stac;
for(int i = 0; i < s.size(); i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
stac.push(s[i]);
else {
if(stac.empty())
return false;
if(s[i] == ')') {
if(stac.top() != '(')
return false;
}
else if(s[i] == ']') {
if(stac.top() != '[')
return false;
}
else if(s[i] == '}') {
if(stac.top() != '{')
return false;
}
stac.pop();
}
}
return stac.empty() ? true : false;
}
};