Java balanced expressions check {[()]}

后端 未结 30 869
傲寒
傲寒 2020-12-04 17:17

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 expressio

相关标签:
30条回答
  • 2020-12-04 17:25

    Using switch-case for better readability and handling of other scenarios:

    import java.util.Scanner;
    import java.util.Stack;
    
    public class JavaStack
    {
        private static final Scanner scanner = new Scanner(System.in);
    
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            while (sc.hasNext()) {
                String input = sc.next();
                System.out.println(isStringBalanced(input));
            }
            scanner.close();
    
        }
    
        private static boolean isStringBalanced(String testString)
        {
            Stack<Character> stack = new Stack<Character>();
            for (char c : testString.toCharArray()) {
                switch (c) {
                    case '[':
                    case '(':
                    case '{':
                        stack.push(c);
                        break;
                    case ']':
                        if (stack.isEmpty() || stack.pop() != '[') {
                            return false;
                        }
                        break;
                    case ')':
                        if (stack.isEmpty() || stack.pop() != '(') {
                            return false;
                        }
                        break;
                    case '}':
                        if (stack.isEmpty() || stack.pop() != '{') {
                            return false;
                        }
                        break;
                    default:
                        break;
                }
            }
            // stack has to be empty, if not, the balance was wrong
            return stack.empty();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:26

    You are pushing i - the index - on the stack, and comparing against ch. You should push and pop ch.

    0 讨论(0)
  • 2020-12-04 17:26

    Late Post.

    package com.prac.stack;
    
    public class BalanceBrackets {
    
    public static void main(String[] args) {
        String str = "{()}[]";
        char a[] = str.toCharArray();
        System.out.println(check(a));
    }
    
    static boolean check(char[] t) {
        Stackk st = new Stackk();
        for (int i = 0; i < t.length; i++) {
            if (t[i] == '{' || t[i] == '(' || t[i] == '[') {
                st.push(t[i]);
            }
            if (t[i] == '}' || t[i] == ')' || t[i] == ']') {
                if (st.isEmpty()) {
                    return false;
                } else if (!isMatching(st.pop(), t[i])) {
                    return false;
                }
            }
        }
    
        if (st.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
    
    static boolean isMatching(char a, char b) {
        if (a == '(' && b == ')') {
            return true;
        } else if (a == '{' && b == '}') {
            return true;
        } else if (a == '[' && b == ']') {
            return true;
        } else {
            return false;
        }
    }
    
    }
    
    0 讨论(0)
  • 2020-12-04 17:30
    import java.util.Objects;
    import java.util.Stack;
    
    public class BalanceBrackets {
    
        public static void main(String[] args) {
            String input="(a{[d]}b)";
            System.out.println(isBalance(input));  ;
        }
    
        private static boolean isBalance(String input) {
            Stack <Character> stackFixLength = new Stack();
    
            if(input == null || input.length() < 2) {
                throw  new IllegalArgumentException("in-valid arguments");
            }
    
            for (int i = 0; i < input.length(); i++) {
    
                if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
                    stackFixLength.push(input.charAt(i));
                }
    
                if (input.charAt(i) == ')' || input.charAt(i) == '}' || input.charAt(i) == ']') {
    
                    if(stackFixLength.empty()) return false;
    
                    char b = stackFixLength.pop();
    
                    if (input.charAt(i) == ')' && b == '(' || input.charAt(i) == '}' && b == '{' || input.charAt(i) == ']' && b == '[') {
                        continue;
                    } else {
                        return false;
                    }
                }
            }
    
            return stackFixLength.isEmpty();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:33

    Similar to one of the code above in JAVA but It needs one more else statement added in order to avoid stack comparison with characters other than braces :

    else if(bracketPair.containsValue(strExpression.charAt(i)))

    public boolean isBalanced(String strExpression){
     Map<Character,Character> bracketPair = new HashMap<Character,Character>();
      bracketPair.put('(', ')');
      bracketPair.put('[', ']');
      bracketPair.put('{', '}');
      Stack<Character> stk = new Stack<Character>();
            for(int i =0;i<strExpression.length();i++){
                if(bracketPair.containsKey(strExpression.charAt(i)))
                    stk.push(strExpression.charAt(i));
                else if(bracketPair.containsValue(strExpression.charAt(i))) 
                    if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
                    return false;
            }
    
            if(stk.isEmpty())
                return true;
                else
                    return false;
            }
    
    0 讨论(0)
  • 2020-12-04 17:35

    Considering string consists only of '(' ')' '{' '}' '[' ']'. Here is a code method that returns true or false based on whether equation is balanced or not.

    private static boolean checkEquation(String input) {
    
        List<Character> charList = new ArrayList<Character>();
    
        for (int i = 0; i < input.length(); i++) {
    
            if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
                charList.add(input.charAt(i));
            } else if ((input.charAt(i) == ')' && charList.get(charList.size() - 1) == '(')
                    || (input.charAt(i) == '}' && charList.get(charList.size() - 1) == '{')
                    || (input.charAt(i) == ']' && charList.get(charList.size() - 1) == '[')) {
                charList.remove(charList.size() - 1);
            } else
                return false;
    
        }
    
        if(charList.isEmpty())
            return true;
        else
            return false;
    }
    
    0 讨论(0)
提交回复
热议问题