Checking the validity of parentheses in JavaScript


We are required to write a JavaScript function that takes in a string str containing just the characters −

'(', ')', '{', '}', '[' and ']'

Our function should determine if the input string is valid.

An input string is valid if −

  • Open brackets must be closed by the same type of brackets.

  • Open brackets must be closed in the correct order.

For example −

  • "()" is a valid parenthesis

  • "()[]{}" is a valid parentheses

  • "(]" is an invalid parenthesis

Example

The code for this will be −

const str = "()[]{}";
const isValid = (str = '') => {
   const map=new Map();
   map.set('{','}');
   map.set('(',')');
   map.set('[',']');
   const b=[];
   for(let i=0;i<str.length;i++){
      if(map.has(str.charAt(i))){
         b.push(str.charAt(i));
      } else{
         let pop=b.pop();
         if(map.get(pop)!==str.charAt(i)){
            return false;
         }
      };
   };
   return b.length===0;
};
console.log(isValid(str));

Output

And the output in the console will be −

true
false

Updated on: 24-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements