-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path224C. Bracket Sequence.cpp
58 lines (50 loc) · 1.09 KB
/
224C. Bracket Sequence.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
/*
Idea:
- Extract all right substrings in the origin string then try to concatinate them.
*/
#include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 10;
char s[N];
int n, cs[N];
stack<pair<int, int> > st;
int main() {
scanf("%s", s);
n = strlen(s);
for(int i = 0; i < n; ++i) {
if(s[i] == '(' || s[i] == '[')
st.push({i, s[i]});
else {
if(!st.empty() &&
((s[i] == ']' && '[' == st.top().second) ||
(s[i] == ')' && '(' == st.top().second))) {
cs[st.top().first] = 1;
cs[i] = 1;
st.pop();
} else {
while(!st.empty())
st.pop();
}
}
}
int res = 0, start = -1, end = -1;
for(int i = 0; i < n; ++i)
if(cs[i] == 1) {
int j = i;
for(; j < n && cs[j] == 1; ++j);
int cnt = 0;
for(int k = i; k < j; ++k)
cnt += s[k] == '[';
if(cnt > res)
res = cnt, start = i, end = j;
i = j;
}
if(res > 0) {
printf("%d\n", res);
for(int i = start; i < end; ++i)
putchar(s[i]);
puts("");
} else
puts("0\n");
return 0;
}