How to check if a String is balanced?

前端 未结 8 1015
逝去的感伤
逝去的感伤 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:53

    Following is a Java code sample to detect if a string is balanced.

    http://introcs.cs.princeton.edu/java/43stack/Parentheses.java.html

    The idea is that -

    • For each opening brace ( [ {, push it on the stack.
    • For closing brace ) ] }, try to pop a matching opening brace ( [ } from stack. If you can't find a matching opening brace, then string is not balanced.
    • If after processing the complete string, stack is empty then string is balanced. Otherwise string is not balanced.
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题