DEV Community

Anuj Srivastav
Anuj Srivastav

Posted on • Edited on

LeetCode — Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Solution

var isValid = function(s) {
let arr = [];
const bracketObj = {
"{":"}",
"(":")",
"[":"]"
}
for(let i=0;i<s.length;i++){
   if(s[i] =="{"|| s[i] == "(" || s[i] == "["){
       arr.push(s[i]);
   }else if(bracketObj[arr.pop()] !== s[i]){
   return false;
   }
}
return arr.length === 0 ;
};
Enter fullscreen mode Exit fullscreen mode

Test Cases Example

Input: s = "()"
Output: true

Input: s = "()[]{}"
Output: true

Input: s = "(]"
Output: false

Input: s = "([)]"
Output: false


Input: s = "(("
Output: false`
**
CodeSandBox Link **

https://codesandbox.io/s/valid-parentheses-1gs732?file=/src/index.js

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay