Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Last active October 4, 2017 17:00
Show Gist options
  • Save rebolyte/63adaa244df468190420acc74417334c to your computer and use it in GitHub Desktop.
Save rebolyte/63adaa244df468190420acc74417334c to your computer and use it in GitHub Desktop.
matching brackets
// https://www.reddit.com/r/javascript/comments/4eb61r/interview_exercise_feedback/
function isBalanced(str) {
var dict = {
'{': '}',
'(': ')',
'[': ']'
};
var stack = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === dict[stack[stack.length - 1]]) {
stack.pop();
} else {
stack.push(str[i]);
}
}
return stack.length === 0 ? true : false;
}
let last = arr => arr[arr.length - 1];
function isBalanced2(str) {
let dict = {
'{': '}',
'(': ')',
'[': ']'
};
let stack = [];
str.split('').forEach(ch => {
if (ch === dict[last(stack)]) {
stack.pop();
} else {
stack.push(ch);
}
});
return stack.length === 0;
}
console.log(isBalanced2('')); // true
console.log(isBalanced2('()()')); // true
console.log(isBalanced2('{{[]()}}')); // true
console.log(isBalanced2('([)]')); // false
console.log(isBalanced2(']]')); // false
// console.log(isBalanced('((((()))))')); // true
// console.log(isBalanced('({][]})')); // false
// console.log(isBalanced('(')); // false
// console.log(isBalanced(']')); // false
// console.log('');
function isBalanced3(str) {
const dict = {
'{': '}',
'(': ')',
'[': ']'
};
let stack = [];
for (let i = 0, l = str.length; i < l; i++) {
if (str[i] === dict[last(stack)]) {
stack.pop();
} else if (str[i] in dict) {
stack.push(str[i]);
} else {
// if we find a closing bracket and we don't have a match for it,
// we know we have an imbalance
return false;
}
}
return stack.length === 0;
}
def is_balanced(s):
d = {
'{': '}',
'(': ')',
'[': ']'
}
stack = []
for ch in s:
if (len(stack) > 0) and (ch == d.get(stack[-1])):
stack.pop()
elif (ch in d):
stack.append(ch)
else:
return False
return len(stack) == 0
assert is_balanced('') # True
assert is_balanced('()()') # True
assert is_balanced('{{[]()}}') # True
assert not is_balanced('([)]') # False
assert not is_balanced(']]') # False
assert is_balanced('((((()))))') # True
assert not is_balanced('({][]})') # False
assert not is_balanced('(') # False
print('Passed!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment