算法竞赛进阶指南---0x18(栈)括号画家

题面

在这里插入图片描述

题解

  1. 大多数括号匹配的题都是与栈有关联的,一个完美的括号序列,总是左右括号能完全匹配,所以如果一段括号序列为完美序列,那么最好扫描完栈一定是空的
  1. 此题我们是求一段序列中的最长完美序列,那么我们就将左括号入栈,遇到右括号就判断是否能和栈顶括号匹配,如果不能就入栈,每次都更新一下最大匹配长度即可

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>


using namespace std;
const int N = 1e5 + 10;

char str[N];

int main() {
    
    

    cin >> str;
    int n = strlen(str);
    int res = 0;
    stack<int> stk;
    for (int i = 0; i < n; i++) {
    
    
        if (stk.size()) {
    
    
            char c1 = str[i];
            char c2 = str[stk.top()];
            if ((c1 == ')' && c2 == '(') || (c1 == '}' && c2 == '{') || (c1 == ']' && c2 == '[')) {
    
    
                stk.pop();
            } else {
    
    
                stk.push(i);
            }
        } else {
    
    
            stk.push(i);
        }
        if (stk.size()) res = max(res, i - stk.top());
        else res = max(res, i + 1);
    }
    cout << res << endl;

    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/113851057