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;
}
}