Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java program to check valid Balanced parentheses

Balanced parentheses:
  •   A string which contains below characters in correct order.
  •  "{}" "[]" "()"
  • We need to check whether given string has valid order of parenthesis order.
  • If the parenthesis characters are placed in order then we can say its valid parentheses or balanced parentheses.
  • If the parentheses characters are not in correct order or open and close then we can say it is not balanced or invalid parenthesis.
  • Program to check given string has a valid parenthesis or not.

#1: Java example program to check given string has valid parenthesis or not.


  1. package instanceofjava;

  2. import java.util.Stack;

  3. public class BalancedParenthensies {

  4. public static void main(String[] args) {
  5. System.out.println(checkParenthensies("{(xxx,yyy)}"));
  6. System.out.println(checkParenthensies("{)(acd,bcvfs}"));
  7. System.out.println(checkParenthensies("{(xxx},yyy)"));
  8. System.out.println(checkParenthensies("[(xxx),yyy]"));
  9. }
  10. public static boolean checkParenthensies(String str) {
  11.         Stack object  = new Stack();
  12.         for(int i = 0; i
  13.             char ch = str.charAt(i);
  14.             if(ch == '[' || ch == '(' || ch == '{' ) {     
  15.             object.push(ch);
  16.             } else if(ch == ']') {
  17.                 if(object.isEmpty() || object.pop() != '[') {
  18.                     return false;
  19.                 }
  20.             } else if(ch == ')') {
  21.                 if(object.isEmpty() || object.pop() != '(') {
  22.                     return false;
  23.                 }           
  24.             } else if(ch == '}') {
  25.                 if(object.isEmpty() || object.pop() != '{') {
  26.                     return false;
  27.                 }
  28.             }
  29.         }
  30.         return object.isEmpty();
  31.     }
  32. }

Output:
  1. true
  2. false
  3. false
  4. true





This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Java program to check valid Balanced parentheses

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×