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

原文链接:Valid Parentheses | LeetCode | Java

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容