用栈储存左右括号的序号,若左右括号匹配,则出栈。每处理一个字符就更新一次答案。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
int main(){
string s;
int ans=0;
cin>>s;
stack<int> st;
for(int i=0;i<s.size();i++){
if(!st.empty()&&(s[i]==')'&&s[st.top()]=='('||s[i]==']'&&s[st.top()]=='['||s[i]=='}'&&s[st.top()]=='{')){
st.pop();//若栈不为空且当前处理的字符为右括号且与栈顶的左括号匹配,则出栈。
}
else st.push(i);//否则将当前字符序号(从0开始)进栈
if(st.empty()) ans=max(ans,i+1);//栈空则该字符及之前的字符都匹配
else ans=max(ans,i-st.top());//更新该字符序号到栈顶序号的距离,即为匹配长度
}
printf("%d",ans);
return 0;
}