Valid Parentheses | LeetCode | Java

Tanuja V - Jun 4 - - Dev Community
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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player