Implement function verify(text) which verifies whether parentheses within text are correctly nested. You need to consider three kinds: (), [], <> and only these kinds. Examples:
verify("---(++++)----") -> 1
verify("") -> 1
verify("before ( middle []) after ") -> 1
verify(") (") -> 0
verify("<( >)") -> 0
verify("( [ <> () ] <> )") -> 1
verify(" ( [)") -> 0
I tried to do it as below but the interviewer told that there was an error and is giving me a second chance.
function verify(text) {
const stack = [];
for (const c of text) {
if (c === '(') stack.unshift(')')
else if (c === '[') stack.unshift(']')
else if (c === '<') stack.unshift('>')
else if (c === stack[0]) stack.shift()
else if (c === ')' || c === ']' || c === '>') return 0
}
return 1
}
const test_inputs = ["---(++++)----", "", "before ( middle []) after ", ") (", "<( >)", "( [ <> () ] <> )", " ( [)"]
for (const i in test_inputs) {
console.log(verify(i))
}
The output is:
1
1
1
1
1
1
1