题解 | 最长的括号匹配用栈记录左括号位置然后依次匹配就行
最长的括号匹配
https://www.nowcoder.com/practice/a88e0c404ee9428f9f741d96847499b7
#include<stdio.h>
#include<string.h>
int main() {
char s[30000];
scanf("%s", &s);
int n = strlen(s);
int stack[n], top = -1, ans = 0;
for (int i = 0; i < n; i++) stack[i] = 0;
stack[++top] = -1;
for (int i = 0; i < n; i++) {
if (s[i] == '(') stack[++top] = i;
else {
--top;
if (top == -1) stack[++top] = i;
else if (i - stack[top] > ans) ans = i - stack[top];
}
}
printf("%d\n", ans);
return 0;
}