CopyPastehas never been so tasty!

paramatch

by anonymous

  • 0
  • 0
184 views
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();

      }

//-----------------------------------------

2:

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;

     }

   }

//---------------------------------------------
3:

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

    }


}