How to check if a String is balanced?

前端 未结 8 1067
逝去的感伤
逝去的感伤 2020-12-06 11:57

I want to test if an input String is balanced. It would be balanced if there is a matching opening and closing parenthesis, bracket or brace.

example:
{} bal         


        
8条回答
  •  囚心锁ツ
    2020-12-06 12:54

    I wrote this code to solve this problem using only an integer (or maybe a byte) variable per bracket type.

    public boolean checkWithIntegers(String input) {
    
        int brackets = 0;
    
        for (char c: input.toCharArray()) {
    
            switch (c) {
    
                case '(':
    
                    brackets++;
    
                    break;
    
                case ')':
    
                    if (brackets == 0)
                        return false;
    
                    brackets--;
    
                    break;
    
                default:
    
                    break;
            }
        }
    
    
        return brackets == 0;
    }
    
    public static void main(String... args) {
    
        Borrar b = new Borrar();
        System.out.println( b.checkWithIntegers("") );
        System.out.println( b.checkWithIntegers("(") );
        System.out.println( b.checkWithIntegers(")") );
        System.out.println( b.checkWithIntegers(")(") );
        System.out.println( b.checkWithIntegers("()") );
    
    }
    

    OBS

    1. I'm assuming that an empty string is balanced. That can be changed with just a previous check.
    2. I'm using only one type of bracket example, but other types can be added quickly just adding another case switch.

    Hope this help. Cheers!

提交回复
热议问题