The Programming Project: Data Structure
Showing posts with label Data Structure. Show all posts
Showing posts with label Data Structure. Show all posts

Tuesday, August 27, 2013

Parentheses Checking

Given an expression string exp, write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[","]” are correct in exp. For example, the program should print true for exp = “[a+{b-(c-(d-e)*d)+w)}+q]” and false for exp = “[(])”



 import java.util.*;

public class Parentheses
   {
   public static void main(String[] args)
{
int n,i,pos,posm,t;
boolean flag=true;
char[] symb={'(','{','[',']','}',')'};
char tmp;
Scanner in = new Scanner(System.in);
String expression;
System.out.println(" Enter the expression:");
expression=in.nextLine();
System.out.println(" Entered expression is:"+expression);
n=expression.length();
Stack s = new Stack(n);
System.out.println("");
for(i=0;i<n;i++)
{
pos=0;
posm=0;
if(expression.charAt(i)==symb[0] || expression.charAt(i)==symb[1] || expression.charAt(i)==symb[2] )
{
s.push(expression.charAt(i));

}
if(expression.charAt(i)==symb[3] || expression.charAt(i)==symb[4] || expression.charAt(i)==symb[5] )
{
if(s.isempty()==true)
{
flag=false;
break;
}
else
{
tmp=s.pop();
for(t=0;t<3;t++)
if(symb[t]==tmp)
pos=t;
for(t=3;t<6;t++)
if(symb[t]==expression.charAt(i))
posm=t;
if(pos+posm!=5)
{
flag=false;
break;
}
}
}
 

}
if(s.isempty()==false)
flag=false;
if(flag==true)
System.out.println(" Valid Expression:");
else
System.out.println(" Invalid Expression:");
in.close();
}

  }
class Stack
{
public Stack(int a)
{
top=-1;
n=a;
stack = new char[n];
}
public void push(char x)
{
stack[++top]=x;
}
public char pop()
{
return (stack[top--]);
}
public char stacktop()
{
return (stack[top]);
}
public boolean isempty()
{
return ( top==-1 ? true: false);
}
private int top;
private int n;
private char[] stack;

}



Sunday, August 18, 2013