解题思路:用一个栈保存未匹配的左括号,然后遍历字符串,判断当前字符是左括号还是右括号。如果当前字符是左括号,那么将其入栈;如果当前字符是右括号且栈非空,那么判断是否与栈顶的左括号相匹配,如果匹配则弹出栈顶元素,不匹配则返回false。最后判断栈是否为空。
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
int len = s.length();
for(int i = 0;i < len;i++){
if(s[i] == '{' || s[i] == '[' || s[i] == '(') {
stk.push(s[i]);
} else if(stk.size() && isPair(stk.top(), s[i])){
stk.pop();
} else {
return false;
}
}
return stk.empty();
}
private:
bool isPair(char x, char y) {
if( (x == '{' && y == '}') ||
(x == '[' && y == ']') ||
(x == '(' && y == ')') ){
return true;
}
else return false;
}
};