题目如下:
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.
本题很容易想到用到栈,对于给定的字符串,遍历其每一个元素,如果遇到 ‘(’ ‘[’ ‘{’ 就将他们压入栈中,如果遇到 ‘)’ ‘]’ ‘}’,就取栈顶元素,看是否与其匹配,如果匹配则将栈顶元素pop掉,如果不匹配,返回false;遍历到最后检查栈是否为空,如果为空则为true,否则则为false;具体实现如下:
class Solution {
public:
bool isValid(string s) {
int n = s.size();
stack<char> a;
for (int i = 0; i < n; i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
a.push(s[i]);
}
if(s[i] == ')') {
if(!a.empty() && a.top() == '(') {
a.pop();
}
else return false;
}
if(s[i] == '}') {
if(!a.empty() && a.top() == '{') {
a.pop();
}
else return false;
}
if(s[i] == ']') {
if(!a.empty() && a.top() == '[') {
a.pop();
}
else return false;
}
}
return a.empty();
}
};