class Solution {
bool check(char ch1,char ch2) {
if(ch1 == ')' && ch2 != '(') return true;
else if(ch1 == ']' && ch2 != '[') return true;
else if(ch1 == '}' && ch2 != '{') return true;
else return false;
}
public:
bool isValid(string s) {
if (s.size() < 2) return false;
stack<char> stk;
for (int i = 0; i < s.size(); ++i) {
if (stk.empty()) {
if(s[i] == ')' || s[i] == '}' || s[i] == ']') return false;
else stk.push(s[i]);
}else{
if(s[i] == '(' || s[i] == '{' || s[i] == '[') stk.push(s[i]);
else{
if(check(s[i],stk.top())) return false;
else{
stk.pop();
continue;
}
}
}
}
return stk.empty() ? true : false;
}
};
时间复杂度高
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if (n % 2 != 0) return false;
stack<char> stk;
for (int i = 0; i < n; ++i) {
if (s[i] == '(') stk.push(')');
else if (s[i] == '[') stk.push(']');
else if (s[i] == '{') stk.push('}');
else if (stk.empty() || s[i] != stk.top()) return false;
else stk.pop();
}
return stk.empty();
}
};