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<Character> object  = new Stack<Character>();
  12.         for(int i = 0; i < str.length(); 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

check valid java balanced parenthesis


Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu