DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 20. Valid Parentheses

Approach

We loop through chars of s , if its a closing bracket we compare with last element in stack , it should be appropriate as define in map otherwise we return false

Javascript Code

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
    const myMap = {
        "}": "{",
        "]": "[",
        ")": "("
    };
    let myStack = [];

    for (let char of s) {
        if (char in myMap) {  // If it's a closing bracket
            if (myStack.length === 0 || myStack.pop() !== myMap[char]) {
                return false;
            }
        } else {  // If it's an opening bracket
            myStack.push(char);
        }
    }

    return myStack.length === 0;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay