洛谷
这题我们可以模拟一下。发现如果当前是对映右括号中出现的一个右括号,那么要找匹配的左括号,一定是对映左括号中最后出现的左括号。
如 (((((())
,当我们想要为第一个出现的右括号匹配时,我们要找的是最后一个左括号。为第二个出现的右括号匹配时,我们要找的是倒数第二个左括号。
那么我们就可以用栈来完成模拟操作。
#include<bits/stdc++.h>
#include<cstring>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#include<map>
#define ll long long
using namespace std;
const int N=1e5+10;
const int M=2023;
const int inf=0x3f3f3f3f;
char a[N];
int ans,x,y,z,num;
stack<int> s;
int main()
{
scanf("%s",a);
for(int i=0;i<strlen(a);i++)
{
if(s.size())
{
char x=a[s.top()];
if((a[i]==')' and x=='(') or (a[i]==']' and x=='[') or (a[i]=='}' and x=='{'))//寻找匹配的括号
{
s.pop();
}
else//没有就插入
{
s.push(i);
}
}
else
{
s.push(i);
}
if(!s.size())//都可以匹配
{
ans=max(ans,i+1);//i从0开始
}
else
{
ans=max(ans,i-s.top());//这中间的括号都可以匹配上
}
}
printf("%d",ans);
return 0;
}