Created
June 2, 2022 00:19
-
-
Save omokehinde/a59b11db9864426637e7a0f404d230a2 to your computer and use it in GitHub Desktop.
A function that checks if a string containing brackets is valid.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isValid = (s) => { | |
let bracket_obj = { | |
"[":"]", | |
"(":")", | |
"{":"}" | |
}; | |
let open_brackets = []; | |
for (let i = 0; i < s.length; i++) { | |
if (s[i] in bracket_obj) { | |
open_brackets.push(s[i]); | |
} else if(open_brackets.length===0 && bracket_obj[s[i]]=== undefined) { | |
return false; | |
} else if(bracket_obj[open_brackets[open_brackets.length-1]]===s[i]){ | |
open_brackets.pop(); | |
} else { return false; } | |
} | |
return open_brackets.length === 0; | |
}; | |
console.log(isValid("([{})]")) | |
console.log(isValid("({]})")) | |
console.log(isValid("([{}])")) | |
console.log(isValid("({[]})")) | |
console.log(isValid("()[]{}")) | |
console.log(isValid("}")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment