DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Algorithm part-2 : Brackets Validation

Hello guys, Let's continue our algorithm series...
Today i am going to show you how to solve valid Brackets problem. Let's discuss this problem first.

In this problem we are given brackets in form of String.We have to find out if they are valid or not.

Example

{([])}    : Valid
{(}}      : Invalid
{(}       : Invalid
{         : Invalid
}         : Invalid
{([)]}    : Invalid 
Enter fullscreen mode Exit fullscreen mode

Let's see the solution.

 public boolean validBrackets(String brackets) {
        char[] arr = brackets.toCharArray();

        Stack<Character> stack = new Stack<>();
        for (Character ch : arr) {
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                } else {
                    if (
                       ch == ')' && stack.peek() == '(' || 
                       ch == '}' && stack.peek() == '{' || 
                       ch == ']' && stack.peek() == '['
                      ){
                        stack.pop();
                    }else{
                        return false;
                    }
                }
            }

        }
        return stack.isEmpty();
    }
Enter fullscreen mode Exit fullscreen mode

Hope this post was useful. Thank you ❤.

Top comments (0)