method 1: 栈
遍历字符串
遇到左括号就压栈;遇到右括号,若栈不为空,就将栈顶的左括号取出,匹配返回一个bool值。
若直至遍历结束都没有发生错误且栈为空,则匹配成功。
(()){}
(qw){[]}
#include<iostream>
#include<stack>
using namespace std;
bool left(char s) {
return s=='(' || s=='{' || s=='[';
}
bool right(char s) {
return s==')' || s=='}' || s==']';
}
bool check(char a,char b) {
return (a=='(' && b==')') || (a=='{' && b=='}') || (a=='[' && b==']');
}
bool match(string s)
{
stack<char> p;
for(int i=0; i<s.size(); i++)
{
if(left(s[i])) {
p.push(s[i]);
}else if(right(s[i])) {
if(!p.empty() && check(p.top(),s[i])) { //栈不空,且匹配正确
p.pop();
} else {
return false; //不匹配,直接返回false
}
}
}
if(!p.empty()) return false; //栈不空,说明存在没有匹配的左括号,返回false
return true; //全都匹配成功
}
-------
针对只有'('、')'的情况
顺序遍历,计数匹配
顺序遍历。遇到左括号,count+1;遇到右括号,count-1。过程中出现count<0,返回false。最终 return count==0
bool isValid(string s)
{
int count = 0;
for(auto & e : s) {
if(e == '(') {
count++;
} else if(e == ')') {
count--;
if(count < 0) {
return false;
}
}
}
return count==0;
}