Question: There is a Series containing only, ask the maximum number of square brackets in all substrings that can be paired with each other in the left and right brackets of the sequence, and output the corresponding substrings.
Practice: Use a stack for maintenance. This element will pop up every time if there is a right brace that can be paired with the elements at the top of the stack. If the elements pop up at this time represent square brackets, record the subscript that appears at this time. Otherwise, the element is pushed to the stack. Of course we press the subscript of the current element into the stack. After a complete sequence is processed, the scripts in the stack store all the parentheses that cannot be paired. Each two subscript can be paired and meet the conditions. In this way, we only need to compare the square brackets that can contain the most between every two subscripts. To calculate the number of square brackets in a clip, we only need to use the subscript of the square brackets recorded earlier to calculate a prefix sum.
Code:
# Include <iostream> # include <cstdio> # include <algorithm> # include <cstring> # define n 110010 using namespace STD; char a [n]; int sta [N]; int vis [N]; int ans, L, R; int main () {scanf ("% s", a); int Len = strlen (); int tail = 1; for (INT I = 0; I <Len; I ++) {If (tail = 1) {sta [tail ++] = I; vis [I] + = vis [I-1]; continue;} if (a [I] = '(') {sta [tail ++] = I ;} if (A [I] = ') {if (a [sta [tail-1] =' (') tail --; else sta [tail ++] = I;} if (a [I] = '[') {sta [tail ++] = I ;} if (A [I] = ']') {if (a [sta [tail-1] = '[') {tail --; vis [I] = 1;} else sta [tail + +] = I;} vis [I] + = vis [I-1];} vis [Len] + = vis [len-1]; If (tail = 1) {cout <vis [Len]-vis [0] <Endl; cout <A <Endl; return 0;} sta [tail ++] = Len; STA [0] = 0; For (INT I = 1; I <tail; I ++) {If (ANS <vis [sta [I]-vis [sta [I-1]) {ans = vis [sta [I]-vis [sta [I-1]; If (I-1) L = sta [I-1] + 1; else l = 0; R = sta [I] ;}}cout <ans <Endl; For (INT I = L; I <r; I ++) cout <A [I]; return 0 ;}
Codefroces 223a-bracket sequence [stack optimization]