DEV Community

Tanuja V
Tanuja V

Posted on • Updated on

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

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