题目地址:
https://www.luogu.com.cn/problem/CF5C
题面翻译:
给出一个括号序列,求出最长合法子串和它的数量。
合法的定义:这个序列中左右括号匹配
题目描述:
This is yet another problem dealing with regular bracket sequences.
We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
输入格式:
The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed
1
0
6
10^{6}
106 .
输出格式:
Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing 0 1
.
思路是用栈,遇到左括号则入栈(入下标),遇到右括号的话,如果栈空或者栈顶为右括号,则入栈,否则的话说明栈顶是左括号,产生了匹配,弹出栈顶之后,当前的栈顶即为以当前遍历到的括号为右端点的合法匹配串的左端点的左边一位,从而可以计算长度。代码如下:
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
char s[N];
int stk[N], top;
int maxl, cnt;
int main() {
scanf("%s", s);
for (int i = 0; s[i]; i++) {
if (s[i] == '(') stk[top++] = i;
else {
if (!top || s[stk[top - 1]] == ')') stk[top++] = i;
else {
top--;
int l = top ? stk[top - 1] : -1;
if (i - l > maxl) maxl = i - l, cnt = 1;
else if (i - l == maxl) cnt++;
}
}
}
if (!maxl) cnt = 1;
printf("%d %d\n", maxl, cnt);
}
时空复杂度 O ( n ) O(n) O(n), n n n为括号序列长度。