Last active
February 11, 2022 03:57
-
-
Save jocelo/76dcae2d25d7e5d7fb66e7e45aa0513c to your computer and use it in GitHub Desktop.
balanced-brackets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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