Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Wednesday, 3 July 2013

check parentheses in a string / expression are balanced using Regex / Stack . Find Brackets are matched or not in JAVA Program

One of the interesting  java program given below  that may be asked in core java interview or the same may be given to   students to solve at practical labs

         Write a java program that reads a string (expression) from standard input and find  whether its parentheses "(" , ")" , brackets "[", "]"  and  Braces "{", "}"    are properly balanced or not.  i.e. Every open parentheses"("  , braces "{" and brackets "["  should have closing  parenthesis  ")" , braces "}" and brackets "]" respectively in the right order .   For example, the  program will give output
   true for the following input
              1.   ((29*12)+(54+22))
               2.  {[()()]()}
               3. ((([]{}))((())))
     and false for the following
               1.  [(]).
                2. ((())))
                3.  ((29*12*([5*5+7]*5)) + ((54+22))

Please assume that , '(' , '{' , '[' are open characters and ')' , '}' , ']'  are closing characters . Let us solve the above problem now.
 .
 Method I :   Best way to solve the above problem is using stack data structure .  As we know , stack is a  storage mechanishm that works on  Last -in-First-Out (LIFO) that means  the last item stored on the stack  is the first one to be removed.  For more on Stack , please visit my earlier tutorial Stack a FIFO data structure

How to solve the above problem using stack ?
    1) Read the input string (expression ) from the keyboard
   2) Create a stack object to accept  character only.
    3. Traverse the input string / expression
         a) If the current character is a open (left )  parenthesis '('  or brace '{'  or bracket '['  then push the corresponding closing (right) character (i.e. ')' , '}' , ']')  to the stack. You can push the open chracters.   I have Pushed the closing charaters to the stack instead of left to  reduce the little bit lines of logic.
         b) If the current character is a closing (right) parenthesis ')'  , brace '}' and bracket ']' ,
                         i)  check for the stack is empty , if it is empty , then the parentheses are not balanced  because there is no open characters for the corresponding closing charaters.
                   ii)  if stack is not empty , then check the current character with top character  (get the top character using peek() )  in the stack . If both are equal, then pop the character from the stack and check for the next character.
  4)  Once the traversal of the expression is completed , check for the stack is empty or not . If stack is empty , then parentheses are balanced otherwise not balanced.

The code is as follows .



import java.util.Stack;

import java.util.Scanner;

public class Parentheses1 {



  public static boolean isBalanced1(String exp)  {


      Stack<Character> stack = new Stack<Character>();

 for (int i=0; i<exp.length(); i++) {

  char c = exp.charAt(i);

  switch (c) {

  case '{' : stack.push('}'); break;

  case '(' : stack.push(')'); break;

  case '[' : stack.push(']'); break;

  case ']' : case ')' : case '}' :

   if (stack.isEmpty())

      return false;

   else   if (stack.peek() == c) {

   stack.pop();

   }

   break;

  default : break;

  }

 }

 return stack.isEmpty();

      }

Some of the other tries to solve the above program.

Method II using Regular expression (Regex)  . You can also try without using regex . I have used very simple  regex .  Steps to solve the above problem  are as follows.

1. Remove all characters like digits , operators, etc  except '(', ')' , '{', '}' , '[' , ']' in the expression.
 2. Replace  every occurrence of  '()' , '{}' , '[]'  in the string  with empty string ("")  (i.e  removal of characters)
 3. Repeat the step 2 ,  until you find that nothing has been replaced .
 4. Now check for the expression  is empty or not. If the string is empty , then  parentheses are perfectly  balanced  , otherwise not.

Code is as follows



public static boolean isBalanced2(String exp)  {

String temp="";

while (exp.trim().length() > 0  )

{

exp=exp.replaceAll("[^\\(\\)\\[\\]\\{\\}]", "") ;

exp=exp.replaceAll("\\(\\)", "");

exp=exp.replaceAll("\\{\\}", "");

exp=exp.replaceAll("\\[\\]", "");


if (exp.trim().equals(temp)) break;

temp=exp;

}

if ( exp.trim().length() ==0) return true;

else {

    System.out.println("Unmatched / Unbalanced characters " + exp);

  return false;

     }

   }

Method III :  Using counter . But this method  is not suitable for all situations .   It just checks , whether the expression has equal number of opening and  closing  parentheses or  brackets or braces and does not check the order. For example, consider the following  expression.
  ([{)}]
 The above expression  has the equal number of opening and closing parentheses / brackets / braces . But it is  not in the right order. The right order may be  ([{}])
 This method may be suitable , if you use either   parentheses or  brackets or  braces in the expression.  eg.   ((()(()()))) . Otherwise  the order should be correct, if you use all .

Steps :
              1. Initialize three counters to 0 , one for parentheses, one for braces , and one for bracket
              2. Traverse the expression by a single  character at a time.
  a) If the current character is '(' , '{' , '[' , then   increment the respective counter by one
  b) If the current character is  ')', '}' , ']' , then decrease one from the respective counter variable.
               3. Check whether all the counters are zero or not. If all counters are having 0 , then the parentheses are balanced  , otherwise not . Please always remember limitation using this method.

 Code is as follows.



public static boolean isBalanced3(String exp)  {

int c1=0, c2=0,c3=0;

 for (int i=0; i<exp.length(); i++) {

  char c = exp.charAt(i);

  switch (c) {

  case '{' : c1++; break;

  case '(' : c2++; break;

  case '[' : c3++; break;

  case '}' : c1--; break;

  case ')' : c2--; break;

  case ']' : c3--; break;

  default : break;

  }

     }


if(c1==0 && c2==0 && c3==0)  return true;

else  return false;


      } 

//Main Method to call the above three methods



public static void main(String[] args) {


Scanner sc=new Scanner(System.in).useDelimiter("\n");;
  

String s = sc.next();


 System.out.println("Balanced checking using stack " + isBalanced1(s));

 System.out.println("Balanced checking using regex " + isBalanced2(s));

 System.out.println("Balanced checking using counter " + isBalanced3(s));

    }


No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...