Skip to content

Instantly share code, notes, and snippets.

@omokehinde
Created June 2, 2022 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omokehinde/a59b11db9864426637e7a0f404d230a2 to your computer and use it in GitHub Desktop.
Save omokehinde/a59b11db9864426637e7a0f404d230a2 to your computer and use it in GitHub Desktop.
A function that checks if a string containing brackets is valid.
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