Java balanced expressions check {[()]}

后端 未结 30 1140
傲寒
傲寒 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: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 charList = new ArrayList();
    
        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;
    }
    

提交回复
热议问题