Saturday, July 1, 2017

Balanced String

A program to determine if the parentheses (), the brackets [], and the braces {}, in a string are balanced.

For example:

{{)(}} is not balanced because ) comes before (

({)} is not balanced because) is not balanced between {} and similarly the { is not balanced between ()

[({})] is balanced

{}([]) is balanced

{()}[[{}]] is balanced


import java.util.Stack;

public class BalancedParenthesis {
     public static void main(String[] args) {
          BalancedParenthesis bp = new BalancedParenthesis();
          System.out.println(bp.isBalanced("{{)(}}"));
          System.out.println(bp.isBalanced("({)}"));
          System.out.println(bp.isBalanced("[({})]"));
          System.out.println(bp.isBalanced("{}([])"));
          System.out.println(bp.isBalanced("{()}[[{}]]"));
     }

     public boolean isBalanced(String string) {
          Stack stack = new Stack<>();
          for (String token : string.split("")) {
               if ("(".equals(token) || "[".equals(token) || "{".equals(token)) {
                    stack.push(token);
               } else if (")".equals(token) || "]".equals(token) || "}".equals(token)) {
                    if (stack.isEmpty()) {
                         return false;
                    }
                    String pop = stack.pop();
                    if ((")".equals(token) && !"(".equals(pop))
                              || ("]".equals(token) && !"[".equals(pop))
                              || ("}".equals(token) && !"{".equals(pop))) {
                         return false;
                    }
               }
          }
          return true;
     }
}

Output:
false
false
true
true
true

No comments:

Post a Comment