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 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".
题目大意是给定字符串,输出 “最长的括号匹配串” 的长度和数量。对于这种括号的题目,基本都得维护一个计数器,然后根据计数器的状态去想办法。
对于给定的串,维护一个计数器cnt,遇到'('加一, 遇到')'减一;再记录一下当前照的最长括号匹配串的开始位置start。
当cnt <= 0时是需要特别注意的。
cnt 小于 0 :说明 当前的字符无法作为 括号匹配串的起点,所以start直接跳到下一个字符,并且把cnt置为0
cnt 等于 0 :说明从start到当前字符恰好组成了一个括号匹配串,然后检查这个括号匹配串的长度,是否需要更新结果。
上述算法中的start实际是跳跃的,每次跳跃的都是一个括号匹配串的长度。
那么对于直到结束,cnt还为正的串,最后的结果可能会有问题,例如 “(()” ,
为了解决这个问题,只要把串反过来再来一遍就行了。因为如果一个串是括号匹配的,那么该串从右往左看也必然是括号匹配的。
也就是说把“(()” 反成 “())”
总得来说是贪心的算法,复杂度是O(n)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <stack>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
void solve(char* str, int len, int& sublen, int& subnum) {
int cnt = 0;
int start = 0;
for (int i = 0; i < len; i++) {
cnt += (str[i] == '(' ? 1 : 0);
cnt -= (str[i] == ')' ? 1 : 0);
if (cnt == 0) {
if (i - start + 1 > sublen) {
sublen = i - start + 1;
subnum = 1;
} else if (i - start + 1 == sublen) {
subnum += 1;
}
} else if (cnt < 0) {
start = i + 1;
cnt = 0;
}
}
}
int main() {
char str1[1000005];
char str2[1000005];
scanf("%s", str1);
int len = strlen(str1);
for (int i = 0; i < len; i++) str2[i] = str1[len-i-1] == '(' ? ')' : '(';
int sublen1 = 0, subnum1 = 0, sublen2 = 0, subnum2 = 0;
solve(str1, len, sublen1, subnum1);
solve(str2, len, sublen2, subnum2);
if (sublen1 == 0 && sublen2 == 0) {
printf("0 1\n");
} else if (sublen1 < sublen2) {
printf("%d %d\n", sublen2, subnum2);
} else {
printf("%d %d\n", sublen1, subnum1);
}
return 0;
}