Skip to content

Instantly share code, notes, and snippets.

@z4o4z
Created March 1, 2016 20:26
Show Gist options
  • Save z4o4z/119f3b0dc8c3a9ac4c56 to your computer and use it in GitHub Desktop.
Save z4o4z/119f3b0dc8c3a9ac4c56 to your computer and use it in GitHub Desktop.
let brackets = {
"[": "]",
"{": "}",
"(": ")",
"<": ">"
}
function correctBrackets (str) {
const vals = Object.keys(brackets).map(key => brackets[key]);
const keys = Object.keys(brackets);
if (vals.indexOf(str[0]) + 1) {
return null;
}
let mass = str.split('');
let stack = [];
for (let i = 0; i < mass.length; i++) {
const l = mass[i];
if (keys.indexOf(l) + 1) {
stack.push(l);
} else {
if (stack.length) {
mass[i] = brackets[stack.shift()];
} else {
return null;
}
}
}
if (stack.length) {
return null;
}
return mass.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment