DEV Community

Tanuja V
Tanuja V

Posted on β€’ Edited on

1 1

Valid Parentheses | LeetCode | Java

class Solution {
    public boolean isValid(String s) {

        Stack<Character> stack = new Stack<>();

        for(char ch : s.toCharArray()){
            if(stack.isEmpty())
                stack.add(ch);
            else if(!stack.isEmpty()){
                if(ch==']' && stack.peek()=='[')
                    stack.pop();

                else if(ch=='}' && stack.peek()=='{')
                    stack.pop();

                else if(ch==')' && stack.peek()=='(')
                    stack.pop();

                else
                    stack.push(ch);
            }
        }

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

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

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 (2)

Collapse
 
jabmist profile image
Steve Moulton β€’

Do you need the if part of the else if? it seems redundant since it passed the outer IF part which is the same check.

Collapse
 
tanujav profile image
Tanuja V β€’

We can use else instead of else-if. I wrote for the sake of my understanding (if that's what you are asking) πŸ™‚

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