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 ❤.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs