Last active
September 30, 2022 23:41
-
-
Save victorkurauchi/eeb8bf9d54f3eef30028de818c0951c3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// you can write to stdout for debugging purposes, e.g. | |
// console.log('this is a debug message'); | |
function solution(S) { | |
if (S == '') return 1; | |
let stack = []; | |
// write your code in JavaScript (Node.js 8.9.4) | |
for (let i = 0; i < S.length; i++) { | |
// console.log(S[i]) | |
let bracket = S[i]; | |
if (bracket == '{' || bracket == '(' || bracket == '[') { | |
stack.push(bracket); | |
} else if (bracket == '}' && stack.length) { | |
let popped = stack.pop(); | |
// console.log('popped', popped); | |
if (popped != '{') return 0; | |
} else if (bracket == ']' && stack.length) { | |
let popped = stack.pop(); | |
// console.log('popped', popped); | |
if (popped != '[') return 0; | |
} else if (bracket == ')' && stack.length) { | |
let popped = stack.pop(); | |
// console.log('popped', popped); | |
if (popped != '(') return 0; | |
} | |
} | |
// console.log('Stack', stack); | |
if (!stack.length) return 1; | |
return 0; | |
} | |
/* | |
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: | |
S is empty; | |
S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; | |
S has the form "VW" where V and W are properly nested strings. | |
For example, the string "{[()()]}" is properly nested but "([)()]" is not. | |
Write a function: | |
function solution(S); | |
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise. | |
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above. | |
Write an efficient algorithm for the following assumptions: | |
N is an integer within the range [0..200,000]; | |
string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")". | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment