【CodeForces】CF5C Longest Regular Bracket Sequence

题目地址:

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为括号序列长度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值