I have been posed the following question...
Given a N different open and close braces in a string "( { [ } ] )", check whether the string has matching braces. Return true if the braces match, false otherwise.
Here is the answer I came up with...
function braceeql(braces){
var leftpar = 0;
var rightpar = 0;
var leftbrace = 0;
var rightbrace = 0;
var leftcurl = 0;
var rightcurl = 0;
for(var index = 0; index < braces.length; index++){
if(braces[index] == ')'){
leftpar += 1;
}else if(braces[index] == '('){
rightpar += 1;
}else if(braces[index] == '['){
leftbrace += 1;
}else if(braces[index] == ']'){
rightbrace += 1;
}else if(braces[index] == '{'){
leftcurl += 1;
}else if(braces[index] == '}'){
rightcurl += 1;
}
}
if(leftcurl == rightcurl && leftbrace == rightbrace && leftpar == rightpar){
console.log(true)
}else{
console.log(false)
}
}
This is really meaty piece of code, but it sure as heck works. I am seeing differing opinions about how others attacked this problem, but am left wondering is there a better/cleaner way of solving this algorithm without compromising the big O?
I am very open to suggestions and other ways of looking at this problem.
The following solution has time complexity of O(n)
function isBalanced(str) {
const map = {
'(': ')',
'[': ']',
'{': '}',
};
const closing = Object.values(map);
const stack = [];
for (let char of str) {
if (map[char]) {
stack.push(char);
} else if (closing.includes(char) && char !== map[stack.pop()]) {
return false;
}
}
return !stack.length;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With