xamples
epeat
ode
pproach
ptimize
est
One of your colleagues insists on writing all code in Notepad, resulting in code that won't run because the brackets, braces, and parenthesis are not properly balanced. You decide to write a bracket validator to check whether the brackets /braces/ parenthesis are valid.
[ ] ( ) { }
Consider these to be valid pairs:
[ and ]
( and )
{ and }
Write an efficient function that tells us whether or not an input string's brackets are properly nested.
"{ [ ] ( ) }" should return true
"{ [ ( ] ) }" should return false
"{ [ }" should return false
"{ [ ( [ { ( )[ ]{ } } ] ) ] }" should return true
{ [ ( ( ) )] }
{ [ ( ( ) )] }
{
{ [ ( ( ) )] }
{
{
[
{ [ ( ( ) )] }
{
{
[
(
{ [ ( ( ) )] }
{
{
[
(
(
{ [ ( ( ) )] }
{
{
[
(
(
)
{ [ ( ( ) )] }
The top bracket closes the one below it so remove both
{
[
(
(
)
{ [ ( ( ) )] }
{
(
[
{ [ ( ( ) ) ] }
{
(
)
The top bracket closes the one below it so remove both
[
{ [ ( ( ) )] }
{
[
{ [ ( ( ) ) ] }
{
{
[
]
The top bracket closes the one below it so remove both
{ [ ( ( ) ) ] }
{
{ [ ( ( ) ) ] }
{
{
The top bracket closes the one below it so remove both
}
{ [ ( ( ) ) ] }
We have checked every bracket in the input and since we have no unmatching brackets, we know that the brackets were balanced
What data structure did this approach remind you of ?
What data structure did this approach remind you of ?
a STACK!
function hasBalancedBrackets(inputString) {
var inputBrackets = inputString.match(/[[\](){}]/g);
var bracketPairs = {
'[' : ']',
'(' : ')',
'{' : '}'
};
var brackets = [ ];
if (!inputString.length || !inputBrackets.length)
return true;
inputBrackets.forEach (function (bracket) {
var lastBracket = brackets[brackets.length - 1];
if (bracketPairs[lastBracket] === bracket)
brackets.pop();
else
brackets.push(bracket);
});
return brackets.length === 0;
}
function hasBalancedBrackets(inputString){
var braces = inputString.match(/[[\](){}]/g);
var e;
while ((e = /\(\)/.exec(braces)) || (e = /\[\]/.exec(braces)) || (e = /\{\}/.exec(braces)))
{
braces = braces.replace(e[0], '');
}
return !braces;
}
REPL.IT solutions
- Data structure principles can come in handy even when you are not explicitly creating a certain structure
-You can use arrays and array methods in Javascript to create an array that basically behaves like a stack/queue