Bracket Matching (ii)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.