Matching Brackets Problem

Back to General discussions forum

Mandeep_Verma     2016-01-20 15:03:38
User avatar

I thought about an algorithm to store all the bracket openings in a stack and to pop the stack by one if a closing bracket of same type occurs otherwise to infer that the bracket sequence is wrong.But it does not seem to work PLEASE help! My code is in JAVA: import java.io.*; class brack { public static void brackets()throws IOException { BufferedReader ob=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(ob.readLine()); String x; int top,det,j; char a[]; for(int i=0;i<n;i++) {det=1; x=ob.readLine(); a=new char[x.length()];top=0; for(j=0;j<x.length();j++) { if(x.charAt(j)=='('||x.charAt(j)=='['||x.charAt(j)=='{'||x.charAt(j)=='<') {a[top]=x.charAt(j); top++; } if(x.charAt(j)==')') { if(a[top]=='(') top--; else {det=0; break;}} if(x.charAt(j)=='}') { if(a[top]=='{') top--; else {det=0; break;}} if(x.charAt(j)==']') { if(a[top]=='[') top--; else {det=0; break;}} if(x.charAt(j)=='>') { if(a[top]=='<') top--; else {det=0; break;}} if(top==(-1)) { det=0;}} System.out.print(det+" ");} } }

Please login and solve 5 problems to be able to post at forum