CodeForces

CF5C Longest Regular Bracket Sequence

题目大意:

给出一个括号序列,求出最长合法子串和它的数量。 合法的定义:这个序列中左右括号匹配

思路:

建立一个数组(Array)对应字符串的每一位。

每次遇到左括号把其压入栈中,每次遇到右括号将其和与其匹配的左括号在(Array)中对应位置赋值为(1)

如样例:

String s: )((())))(()())
Array a : 01111110111111

这样就可以将求最长合法子串的问题转化成求最长的连续(1)子段。

Code:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;

string s;
int st[N], top, max_len, cnt;
bool a[N];

int main() {
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> s;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(') st[++top] = i;
        else {
            if (top) {
                a[st[top]] = 1;
                a[i] = 1;
                --top;
            }
        }
    }
    int seq1 = 0;
    for (int i = 0; i <= s.length(); i++) { //多一次循环判断
        if (a[i]) seq1++;
        else {
            max_len = max(seq1, max_len);
            seq1 = 0;
        }
    }
    for (int i = 0; i <= s.length(); i++) {
        if (a[i]) seq1++;
        else {
            if (seq1 == max_len) {
                cnt++;
            }
            seq1 = 0;
        }
    }
    if (max_len) cout << max_len << " " << cnt << endl;
    else cout << 0 << " " << 1 << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/Nepenthe8/p/13953768.html