最长括号匹配

https://www.luogu.com.cn/problem/P1944

遇到左括号加1右括号减1无法判断【(】)的情况

将括号压入栈中来判断是否合法,左括号直接压进去,右括号与栈顶元素比较,匹配则弹出来,不匹配返回不合法

所有括号都扫完之后记得检查栈是否为空

枚举左端点i,从左往右扫,求出i之后的最长括号匹配

优化

a.左端点为右括号直接跳过

b.左端点每次跳到上一个左端点最长括号匹配+1(没有匹配的话初始化为上一个左端点本身)

#include<bits/stdc++.h>
using namespace std;
int s[10000000],ss[10000000],line[10000000],last[10000000],fl[10000000];
char ch[10000000];
int main()
{
	int ans=0,ansl,ansr;
	cin>>ch;
	int chl=strlen(ch);
	for(int i=0;i<chl-ans;i++) last[i]=i;
	for(int i=0;i<chl-ans;i=last[i]+1)
	{
		if(ch[i]==')'||ch[i]==']') continue;
		int cnt=0;
		for(int j=i;j<chl;j++)
		{
			if(ch[j]=='(') line[++cnt]=1;
			if(ch[j]=='[') line[++cnt]=2;
			if(ch[j]==')')
			{
				if(line[cnt]!=1)  break;
				else cnt--;
			}
			if(ch[j]==']') 
			{
				if(line[cnt]!=2) break;
				else cnt--;
			}
			if(cnt==0) 
			{
				last[i]=j;
				if(j-i+1>ans)
				{
					ans=j-i+1;
					ansl=i;
					ansr=j;
				}	
			}
		}
	} 
	for(int i=ansl;i<=ansr;i++)
	cout<<ch[i];
	return 0;
}```
原文地址:https://www.cnblogs.com/qwq-/p/13451764.html