Bracket Matching (ii) time limit:MS | Memory limit:65535 KB Difficulty:6
-
Describe
-
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
Give me the wrong answer first
The basic idea is to use the idea of the stack, from left to right to traverse the right parenthesis, check the closing parenthesis to see if the previous parentheses match, match the words to delete, do not match to add parentheses. After iterating through, add the number plus the number of left brackets that last left unmatched.
#include <iostream>using namespacestd;intCheckConst Char*str) { intRET =0; STD::stringope (str); Auto ITER=Ope.begin (); for(; ITER! =ope.end ();) { Chari = *ITER; if(i = =')') { if(iter = =Ope.begin ()) {ret++; ITER=Ope.erase (ITER); } Else if(* iter-1) !='(') {ret++; ITER=Ope.erase (ITER); } Else{iter= Ope.erase (iter-1); ITER=Ope.erase (ITER); } } Else if(i = =']') { if(iter = =Ope.begin ()) {ret++; ITER=Ope.erase (ITER); } Else if(* iter-1) !='[') {ret++; ITER=Ope.erase (ITER); } Else{iter= Ope.erase (iter-1); ITER=Ope.erase (ITER); } } ElseITER++; } ret+=ope.length (); returnret;}intMain () {intLen = Check ("([)]"); cout<< Len <<Endl; System ("Pause"); return 0;}
There is a clear error, such as [(]]] it is wrong ... to study tomorrow.
Bracket Matching (ii)