Bracket Matching (ii) description
-
give you a string that contains only "(", ")", "[", "]" four symbols, how many parentheses you need to add at least to make these parentheses match.
Such as:
[] is a match
([]) [] is a match
((] is not a match
([)] is
mismatched
Input
-
-
the first line enters a positive integer N, which indicates the number of test data groups (N<=10)
Each set of test data has only one row, is a string s,s contains only the above mentioned four characters, s length does not exceed
-
-
Output
-
-
outputs a positive integer for each set of test data, representing the minimum number of parentheses to be added. One row per set of test outputs
-
-
Sample input
-
-
4[] ([]) [] (([] ([)]
-
-
Sample output
-
-
0032
-
-
Analysis
-
-
You can use a stack-like idea.
-
-
1. If it is ' (' | | ' [' then press the stack.
-
-
2. If it is ') ' | | "] and the top element of the stack matches it to the top pop.
-
-
3. If the counter example of condition 2 goes into a loop, the element currently being read is compared to each element in the stack.
-
-
3.1 If the match jumps out of the loop and sum plus the number of attempts to match.
-
-
3.2 If reading to the bottom of the stack does not match then sum+1.
-
-
4. The output should be the number of elements in the sum+ "stack"
-
-
So actually can not use the stack to do, because to and stack each element to compare each other, the stack does not have this operation, so should use two arrays, to simulate the operation of the stack.
-
-
For example: (the "stack" below should be understood as an array)
-
-
((])) First (press "Stack", (3rd Step), then "]" in the "stack" (compared to the bottom of the stack no element matches (3.2), so sum++, Continue reading)), perform step 2nd.
-
-
The answer to the output is 1.
-
-
([)) First ([Press the "stack", (Perform step 3rd), and then ")" in the "stack" (compare, compare to the first (when the current element matches, jump out of the loop (3.1).)
-
-
The output answer is 1
-
-
Well, wordy so much, I also express not clear, on the code!
-
-
Code
-
-
1#include <cstdio>2#include <cstring>3 intMain () {4 intN;5scanf"%d",&n);6 while(n--){7 Chararry[ the] = {'0'},stack[ the] = {'0'};8scanf"%s", Arry);9 intLen = strlen (arry), i,flag,temp,sum =0;Ten inttop =0, K; One for(i =0; I < len;i++){ ATEMP = flag =0; -K =top; - if(Arry[i] = ='('|| Arry[i] = ='[') thestack[top++] =Arry[i]; - Else if(Arry[i] = =')'&& Stack[top-1] =='('|| Arry[i] = =']'&& Stack[top-1] =='['){ -top--; -}Else{ + while(k!=0){ - if(Arry[i] = =')'&& Stack[k-1] =='('|| Arry[i] = =']'&& Stack[k-1] =='['){ +temp =1; Atop = k-1; at Break; -}Else{ -Flag + =1; - } -k--; - } in if(!temp) -Sum + =1; to Else +Sum + =Flag; - } the } *Sum + =top; $printf"%d\n", sum);Panax Notoginseng } - return 0; the}
Of course, you can also use the idea of DP, first dig a good pit, to study ...
"Stack idea, DP" NYOJ-15 bracket Matching (ii)