T614127 完美的括号区间

· · 个人记录

我们可以声明一个char类型的栈,在遍历所给字符串的过程中,遇见前括号就入栈。遇到后括号时,判断当前栈顶的前括号是否与遇到的后括号相对应,如若对应,则ans+=2,并把栈顶元素弹出,继续访问下一个字符;如不对应,说明从这个字符开始,序列已经变得不“美观”,那么就将ans更新为0,然后将栈清空。最后在遍历完所有字符后,将之前得到的最大值与最后一次得到的最大值做一次max操作,就可以得到最终答案了。


#include <bits/stdc++.h>
using namespace std;
stack<char> S;
int main () {
    string s;
    cin >> s;
    int ans = 0; 
    int sum = 0; 
    for (int i = 0; i < s.size(); i++){
        if (s[i]=='('||s[i]=='['||s[i]=='{'){
            S.push(s[i]); 
        }else {
            if (!S.empty()){
                if((s[i]==')'&&S.top()=='(')||(s[i]==']'&&S.top()=='[')||(s[i]=='}'&&S.top()=='{')){
                    S.pop(); 
                    sum+=2;
                }else {
                    ans=max(fans,ans);
                    sum=0;
                    while(!S.empty()){
                        S.pop(); 
                    }
                }
            }else {
                ans = max(fans,ans);
                fans = 0;
            }
        }
    }
    ans = max(sum,ans);
    cout << ans << endl;
    return 0;
}