还是套路题,左括号就压栈,右括号就取出一个左括号配对,长度就是前面左括号前面已经合法的最长长度+这一部分左右括号,即拼起来,dp[i]存一下i前面的最长合法子段长度
坑点是不存在合法子串要输出0 1,最开始没看到。。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 #include<stack> 6 #define LL long long 7 #define debug(x) cout << "[" << x << "]" << endl 8 using namespace std; 9 10 const int mx = 1e6+10; 11 char a[mx]; 12 int dp[mx]; 13 stack<int> s; 14 15 int main(){ 16 int ans = 0, num = 1; 17 scanf("%s", a+1); 18 int len = strlen(a+1); 19 for (int i = 1; i <= len; i++){ 20 if (a[i] == '(') s.push(i); 21 else if (!s.empty()){ 22 int t = s.top(); s.pop(); 23 dp[i] = dp[t-1]+i-t+1; 24 if (ans == dp[i]) num++; 25 else if (ans < dp[i]) ans = dp[i], num = 1; 26 } 27 } 28 printf("%d %d ", ans, num); 29 return 0; 30 }