patternjavascriptMinor
Balancing Brackets Algorithm: Stack Data Structure
Viewed 0 times
stackbracketsalgorithmstructurebalancingdata
Problem
I am currently refining my understanding of data structures and as such, decided to implement a popular application of the Stack. Below you will find my implementation of the Balancing Symbols algorithm written in JavaScript.
My basic questions are:
My basic questions are:
- How clean would you rate my code?
- Is time complexity O(n): Linear?
- How can I improve?
function isBalanced(arr){
var stack = new Stack();
var last;
arr.forEach(function(curr){
if (curr === '(' || curr === '[' || curr === '{') {
stack.push(curr);
}
if (curr === ')' || curr === ']' || curr === '}') {
last = stack.peek() + curr;
if (last === '()' || last === '[]' || last === '{}') {
stack.pop();
}
}
});
var result = (stack.length() === 0) ? true : false;
console.log(result);
}
var symbols = ['{', '(', ')', ']'];
isBalanced(symbols);Solution
The code looks reasonably clean, IMO. I assume that it is purposely ES5?
I don't know about
You are not returning any value. There is no need for
Some code that you can consider, in ES5.
I don't know about
Stack as it's not a ES5 standard API (that I know of).You are not returning any value. There is no need for
? true : false — just do return stack.length() === 0;.Some code that you can consider, in ES5.
var completes = ['()', '[]', '{}'];
var open = completes.map(function(complete) {
return complete.charAt(0);
});
var close = completes.map(function(complete) {
return complete.charAt(1);
});
function isBalanced(arr) {
var stack = [];
arr.forEach(function(curr) {
if (open.indexOf(curr) !== -1) {
stack.push(curr);
}
if (close.indexOf(curr) !== -1) {
var last = stack.pop();
if (completes.indexOf(last + curr) === -1) {
stack.push(last);
}
}
});
return stack.length === 0;
}
console.log(isBalanced(['{', '(', ')', ']']));
console.log(isBalanced(['[', '(', ')', ']']));Context
StackExchange Code Review Q#141669, answer score: 2
Revisions (0)
No revisions yet.