https://vjudge.net/problem/CodeForces-5Cios
給出一個括號序列,求出最長合法子串和它的數量。 合法的定義:這個序列中左右括號匹配。c++
這個題和普通的括號匹配有區別,並行的括號匹配也能夠存在,好比()()(),這種答案就是長度爲6。數組
用一個數組記錄每一個位置是否匹配,用棧模擬,每遇到一個'('直接將下標入棧,遇到')'就看棧裏面有沒有'(',若是有就將這個位置和他匹配的位置(棧頂)置爲10而後pop,沒有就繼續。spa
而後這個數組就是一片01了,找最長連續1便可,由於1表示這個位置能夠匹配。.net
#include <bits/stdc++.h> using namespace std; #define inf 0x3f3f3f3f #define ll long long const int N = 1e6 + 5; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1.0); #define lowbit(x) (x & (-x)) int a[N]; int main() { std::ios::sync_with_stdio(false); string s; cin >> s; stack<int> st; int l = s.length(); for (int i = 0; i < l; i++) { if (s[i] == '(') st.push(i); else { if (st.size()) a[st.top()] = a[i] = 1, st.pop(); } } int mx = 0, cnt = 0; map<int, int> mp; for (int i = 0; i < l; i++) { if (a[i]) { cnt++; } else { if (cnt >= mx) { mx = cnt; mp[mx]++; } cnt = 0; } } if (cnt >= mx) mx = cnt, mp[mx]++; if (mx == 0) mp[mx] = 1; cout << mx << " " << mp[mx] << endl; return 0; }