Makeinfo Blog

Makeinfo Blog

Valid Parentheses Using Javascript - LeetCode Challenges

Dorothi Viki's photo
Dorothi Viki
·May 16, 2022·

1 min read

Leetcode Problem Question

Main things to note

  • Object We're using Object to save the opening and closing of the parentheses

  • Stack As you know stack works in a LIFO (Last In First Out) manner. So, you can get the last parenthesis you added and then match it with the object value.

stack parenthesis.png

Javascript Solution

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
     let parenthesesMap = { ')': '(', '}': '{', ']': '[' };

  let stack = new Stack();

  //With Mapping
  for (let index = 0; index < s.length; index++) {
    const element = stack.getPopItem();

    if (Object.values(parenthesesMap).includes(s[index])) {
      stack.push(s[index]);
    }
    else if ((element === parenthesesMap[s[index]])) {
      stack.pop();
    } else return false;
  }

  // if Stack has value that means some open parenthesis are there
  return (stack.isEmpty()) ? true : false;
};


const s = "()[{]"
console.log(isValid(s));

class Stack {

    constructor() {
        this.items = [];
    }

    peek(){
        this.items.shift();
    }

    push(element){
        this.items.push(element);
    }

    //Get the last digit
    pop(){
        // console.log(this.items);
        return this.items.pop();
    }

    isEmpty(){
        return (this.items.length === 0)? true:false;
    }

    printStack(){
        console.log(this.items);
    }

    getSize(){
        return this.items.length;
    }

    getPopItem(){
        return this.items[this.items.length -1];
    }
}

Leetcode Result

image.png

 
Share this