-
-
Save wegorich/3c967a18c02dfa68927e676ce830e4e3 to your computer and use it in GitHub Desktop.
Brackets are correctly nested (two different approaches)
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
/** | |
* 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