Java Program to Check for balanced parenthesis by using Stack

Java Program to Check for balanced parenthesis by using Stack – This program checks the balancing of parenthesis in a string taken as input. The string contains only either ‘(‘ or ‘)’. The program returns -1 if the string is not balanced and the count of number of balanced parenthesis if the string is balanced.

Java Program to Check for balanced parenthesis

This program uses a stack. Every time ‘(‘ is encountered, it is pushed to the stack. On encountering ‘)’, pop() is performed. At last the condition for empty stack is checked. If stack is empty and count is returned else -1.

Input 1
(()())
Output 
3

Input 2
(()()
Output
-1

Code:

import java.util.*;
public class parenthesis {
	static int isParenthesis(String str)
	{
	  int count=0;
	  Stack<Character> stack=new Stack<Character>();
	  for(int i=0;i<str.length();i++) 
	  {
	   if(str.charAt(i)=='(')
	   {
	     stack.push(new Character(str.charAt(i)));
	     continue;
	   }
	   if(str.charAt(i)==')')
	   {
	      if(stack.isEmpty())
	      {
	        return -1;
	      }
	     stack.pop();
	     count++;
	   }
	  }
	  if(stack.isEmpty())
	  {
	    return count;
	  }
	  else
	  {
	   return -1;
	  }
	}
	public static void main(String arg[])
	{
		String s="(()())";
		int result=isParenthesis(s);
		System.out.println(result);
	}
}

Output:

Java Program to Check for balanced parenthesis by using Stack

Leave a Reply

Your email address will not be published. Required fields are marked *