-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_balparen_len.cpp
67 lines (57 loc) · 1.03 KB
/
valid_balparen_len.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <cstdio>
#include <deque>
#include <queue>
#include <stack>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <bitset>
#include <list>
#include <set>
#include <map>
using namespace std;
// stack implementation using array.
// one of the application : convert number in binary.
const int N = 100010;
int stk[N], sz;
inline void push(int val) {
stk[sz] = val;
sz++;
}
inline int top() {
if (sz > 0) {
return stk[sz - 1];
}
return -1;
}
inline void pop() {
if (sz > 0) {
sz--;
}
}
inline bool isEmpty() {
return (sz <= 0);
}
char s[N];
// here find longest valid substring.
int main() {
scanf("%s", s);
int len = strlen(s);
push(-1); // for getting length of valid substring for base.
int ans = 0;
for (int i = 0; i < len; i++) {
if (s[i] == '(') {
push(i);
} else if (s[i] == ')') {
pop();
if (isEmpty()) {
push(i);
} else {
ans = max(ans, i - top());
}
}
}
printf("%d\n", ans);
}