Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java balanced expressions check {[()]}

I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.

I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome. pseudocode

Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.

import java.util.*;

public class Expression
{
  Scanner in = new Scanner(System.in);
  Stack<Integer> stack = new Stack<Integer>();



  public boolean check()
  {
    System.out.println("Please enter your expression.");
    String newExp = in.next();
    String[] exp = new String[newExp];
    for (int i = 0; i < size; i++)
    { 


      char ch = exp.charAt(i);
      if (ch == '(' || ch == '[' || ch == '{')
        stack.push(i);
      else if (ch == ')'|| ch == ']' || ch == '}')
      {
        //nothing to match with
        if(stack.isEmpty())
        {  
          return false;
        }
        else if(stack.pop() != ch)
        { 
          return false;
        } 

      }            
    }
    if (stack.isEmpty())
    {
      return true;
    }
    else
    {
      return false;
    }
  }


}
like image 449
Jess Anastasio Avatar asked Apr 20 '14 21:04

Jess Anastasio


People also ask

Is balanced or not in Java?

A string having brackets is said to be balanced if: A matching closing bracket occurs to the right of each corresponding opening bracket. Brackets enclosed within balanced brackets should also be balanced. It should not contain any non-bracket character.

How do you check if a given string contains valid parentheses in Java?

Valid Parentheses solution in Java We iterate over the characters of the string, and for every iteration: if the current character is an opening bracket, we push it in the stack. if the character is a closing bracket, we pop the stack and check if the top of the stack contains its corresponding opening bracket or not.


Video Answer


3 Answers

I hope this code can help:

import java.util.Stack;  public class BalancedParenthensies {      public static void main(String args[]) {          System.out.println(balancedParenthensies("{(a,b)}"));         System.out.println(balancedParenthensies("{(a},b)"));         System.out.println(balancedParenthensies("{)(a,b}"));     }      public static boolean balancedParenthensies(String s) {         Stack<Character> stack  = new Stack<Character>();         for(int i = 0; i < s.length(); i++) {             char c = s.charAt(i);             if(c == '[' || c == '(' || c == '{' ) {                      stack.push(c);             } else if(c == ']') {                 if(stack.isEmpty() || stack.pop() != '[') {                     return false;                 }             } else if(c == ')') {                 if(stack.isEmpty() || stack.pop() != '(') {                     return false;                 }                        } else if(c == '}') {                 if(stack.isEmpty() || stack.pop() != '{') {                     return false;                 }             }          }         return stack.isEmpty();     } } 
like image 188
Smartoop Avatar answered Sep 29 '22 06:09

Smartoop


public static boolean isBalanced(String expression) {   if ((expression.length() % 2) == 1) return false;   else {     Stack<Character> s = new Stack<>();     for (char bracket : expression.toCharArray())       switch (bracket) {         case '{': s.push('}'); break;         case '(': s.push(')'); break;         case '[': s.push(']'); break;         default :           if (s.isEmpty() || bracket != s.peek()) { return false;}           s.pop();       }     return s.isEmpty();   } }  public static void main(String[] args) {     Scanner in = new Scanner(System.in);     String expression = in.nextLine();     boolean answer = isBalanced(expression);     if (answer) { System.out.println("YES");}     else { System.out.println("NO");}  } 
like image 22
Madalina Raicu Avatar answered Sep 29 '22 05:09

Madalina Raicu


The pseudo code equivalent java implementation of the algorithm is java is as follows.

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author Yogen Rai
 */

public class BalancedBraces
{
    public static void main(String[] args) {
        System.out.println(isBalanced("{{}}") ? "YES" : "NO"); // YES
        System.out.println(isBalanced("{{}(") ? "YES" : "NO"); // NO 
        System.out.println(isBalanced("{()}") ? "YES" : "NO"); // YES 
        System.out.println(isBalanced("}{{}}") ? "YES" : "NO"); // NO
    }

    public static boolean isBalanced(String brackets) {
        // set matching pairs
        Map<Character, Character> braces = new HashMap<>();
        braces.put('(', ')');
        braces.put('[',']');
        braces.put('{','}');

        // if length of string is odd, then it is not balanced
        if (brackets.length() % 2 != 0) {
            return false;
        }

        // travel half until openings are found and compare with
        // remaining if the closings matches
        Stack<Character> halfBraces = new Stack();
        for(char ch: brackets.toCharArray()) {
            if (braces.containsKey(ch)) {
                halfBraces.push(braces.get(ch));
            }
            // if stack is empty or if closing bracket is not equal to top of stack,
            // then braces are not balanced
            else if(halfBraces.isEmpty() || ch != halfBraces.pop()) {
                return false;
            }
        }
        return halfBraces.isEmpty();
    }
}
like image 36
Yogen Rai Avatar answered Sep 29 '22 06:09

Yogen Rai