Skip to content

Instantly share code, notes, and snippets.

@jocelo
Last active February 11, 2022 03:57
Show Gist options
  • Save jocelo/76dcae2d25d7e5d7fb66e7e45aa0513c to your computer and use it in GitHub Desktop.
Save jocelo/76dcae2d25d7e5d7fb66e7e45aa0513c to your computer and use it in GitHub Desktop.
balanced-brackets
function balanced(theString) {
const stack = [];
for (let par of theString) {
if (par == '(' || par == '{' || par == '[') {
stack.push(par);
}
if (par == ')') {
const parApertura = stack.pop();
if (parApertura != '(') {
return false;
}
}
if (par == '}') {
const parApertura = stack.pop();
if (parApertura != '{') {
return false;
}
}
if (par == ']') {
const parApertura = stack.pop();
if (parApertura != '[') {
return false;
}
}
}
if (stack.length > 0) {
return false;
}
return true;
}
function balanced($the_string) {
$stack = [];
$len = strlen($the_string);
for ($i=0 ; $i<$len ; $i++) {
$par = $the_string[$i];
if (in_array($par, ['(', '{', '['])) {
array_push($stack, $par);
}
if ($par == ')') {
$parOpen = array_pop($stack);
if ($parOpen != '(') {
return false;
}
}
if ($par == '}') {
$parOpen = array_pop($stack);
if ($parOpen != '{') {
return false;
}
}
if ($par == ']') {
$parOpen = array_pop($stack);
if ($parOpen != '[') {
return false;
}
}
}
if (count($stack) > 0) {
return false;
}
return true;
}
def balanced(the_string):
stack = []
for par in the_string:
if par == '(' or par == '{' or par == '[':
stack.append(par)
if par == ')':
try:
parApertura = stack.pop()
except:
return False
if parApertura != '(':
return False
if par == '}':
try:
parApertura = stack.pop()
except:
return False
if parApertura != '{':
return False
if par == ']':
try:
parApertura = stack.pop()
except:
return False
if parApertura != '[':
return False
if len(stack) > 0:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment