Huawei hands-on exercise questions-bracket matching detection

Source: Internet
Author: User

Question:

Enter a string consisting of common characters and parentheses (including '(', ')', '[', ']'). Verify that the brackets match, if yes, 0 is output; otherwise, 1 is output.

Smple input: dfa (sdf) df [dfds (dfd)] Smple outPut: 0


Analysis: similar to the issue of character matching in parentheses, we can simulate stack operations for verification. This is simple, that is, stack operations.


The Code is as follows:

Package com. wenj. test;

Import java. util. ArrayList;
Import java. util. List;

Public class TestMatchKuohao {

Public static void main (String args []) {
String strIn = "dfa (sdf) df [dfds (dfd)]";

TestMatchKuohao tm = new TestMatchKuohao ();
System. out. println (tm. matchKuohao (strIn ));
}

Public int matchKuohao (String strIn ){
If ("" = strIn | null = strIn) {// empty strings do not match by default
Return 1;
}
String strTemp = strIn;
Char [] strC = strTemp. toCharArray ();

List <Character> cL = new ArrayList <Character> ();
For (int I = 0; I <strC. length; I ++ ){
Char temp = strC [I];
Switch (temp ){
Case '(':
CL. add (temp );
Break;
Case '[':
CL. add (temp );
Break;
Case ')': // when the right parenthesis is encountered, the stack is output.
If (cL. size () = 0) {// if the stack is empty, the parentheses do not match and 1 is returned.
Return 1;
} Else {
Char tempC = cL. get (cL. size ()-1 );
If ('= tempC ){
CL. remove (cL. size ()-1); // stack operation
} Else {
Return 1;
}
}
Break;
Case ']':
If (cL. size () = 0 ){
Return 1;
} Else {
Char tempC = cL. get (cL. size ()-1 );
If ('[' = tempC ){
CL. remove (cL. size ()-1 );
} Else {
Return 1;
}
}
Break;
Default:
Break;
}
}

If (cL. size () = 0)
Return 0;
Else
Return 1;
}
}


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.