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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

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) πŸ™‚

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay