Check balanced brackets, braces, parenthesis

Check balanced brackets, braces, parenthesis

One of the famous interview question asked is to check if the given string has proper completion of string. This question is twisted and asked in various way, either check for brackets or any one of the bracket, braces or parenthesis or all.

Lets see an example to understand how this can be achieved.

public class bracketcheck {
    public static void main(String[] args) {
        boolean state;
        String str1 = "({})[][";
        String str2 = "(abc){avv}[as]";

        state = stringcheck(str1);
        if (state == true) {
            System.out.println("Str1 is Correct string");
        } else {
            System.out.println("Str1 is Incorrect string");
        }
        state = stringcheck(str2);
        if (state == true) {
            System.out.println("Str2 is Correct string");
        } else {
            System.out.println("Str2 is Incorrect string");
        }

    }


    public static boolean stringcheck(String str) {

        char c;
        int x = 0, y = 0, z = 0;
        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (c == '{') {
                x = x + 1;
            } else if (c == '(') {
                y = y + 1;
            } else if (c == '[') {
                z = z + 1;
            } else if (c == '}') {
                x = x - 1;
            } else if (c == ')') {
                y = y - 1;
            } else if (c == ']') {
                z = z - 1;
            }

        }

        if (x == 0 && y == 0 && z == 0) {
            return true;

        } else {
            return false;
        }
    }
}

Output

Str1 is Incorrect string
Str2 is Correct string

Leave a Reply

Your email address will not be published. Required fields are marked *