![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements