class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
stack<char> stk;//匹配括号的问题用栈的方法
int n = s.size();
if (n % 2) {//若n为奇数则必不匹配
return false;;
}
for (int i = 0; i < n; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
stk.push(s[i]);
continue;
}
if(stk.empty()) return false;//如果不是输入且栈为空,则不匹配
if (s[i] == ')') {
if (stk.top() == '(') {
stk.pop();
continue;
} else {
return false;
}
}
if (s[i] == ']') {
if (stk.top() == '[') {
stk.pop();
continue;
} else {
return false;
}
}
if (s[i] == '}') {
if (stk.top() == '{') {
stk.pop();
continue;
} else {
return false;
}
}
}
if(stk.empty())
return true;
else
return false;;
}
};