Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Brackets are correctly nested (two different approaches)
/**
* Implement function check (text) which checks whether brackets within text are correctly nested.
* You need to consider brackets of three kinds: (), [], {}.
*/
/**
* STACK approach
*/
function check(str){
var brackets = "()[]{}",
bracket,
bracketPosition,
stack = [];
for (var i = 0, l = str.length; i < l; i++) {
bracket = str[i];
bracketPosition = brackets.indexOf(bracket);
if (bracketPosition == -1) continue;
if (bracketPosition %2 === 0) {
stack.push(brackets[bracketPosition+1]);
}
else if (stack.pop() !== bracket) {
return false;
}
}
return !stack.length;
}
/**
* REGEXP approach
*/
function check1(str) {
str = str.replace(/[^\(\)\[\]\{\}]/g, '');
var strPrevious = '';
while (str.length != strPrevious.length) {
strPrevious = str;
str = str.replace('()', '').replace('[]', '').replace('{}', '');
}
return !str.length;
}
console.log(check("a(b)")); //true
console.log(check("[{}]")); //true
console.log(check("[(]")); //false
console.log(check("}{")); //false
console.log(check("z([{}-()]{a})")); //true
console.log(check("")); //true
console.log(check("(((}")); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment