DEV Community

Debesh P.
Debesh P.

Posted on

20. Valid Parentheses | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/valid-parentheses/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/valid-parentheses/solutions/7559664/most-optimal-solution-beats-100-all-lang-32y5


leetcode 20


Solution

class Solution {
    public boolean isValid(String s) {

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

        for (char c : s.toCharArray()) {

            if (c == '(') {
                stack.push(')');
            } 
            else if (c == '{') {
                stack.push('}');
            } 
            else if (c == '[') {
                stack.push(']');
            } 
            else {
                if (stack.isEmpty() || stack.pop() != c) {
                    return false;
                }
            }
        }

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

Top comments (0)