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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

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

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay