Implemente la función verificar (texto) que verifica si los paréntesis dentro del texto están anidados correctamente. Debe considerar tres tipos: (), [], <> y solo estos tipos. Ejemplos:
verify("---(++++)----") -> 1 verify("") -> 1 verify("before ( middle []) after ") -> 1 verify(") (") -> 0 verify("<( >)") -> 0 verify("( [ <> () ] <> )") -> 1 verify(" ( [)") -> 0Intenté hacerlo como se muestra a continuación, pero el entrevistador me dijo que hubo un error y me está dando una segunda oportunidad.
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)) }La salida es:
1 1 1 1 1 1 1Lo único malo con su código es que usó int el bucle for in lugar de of .
O se olvidó de verify(test_inputs[i]) en lugar de verify(i) .
Arreglando eso, produce el resultado correcto:
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 s of test_inputs) { console.log(verify(s), s) }Podemos usar las funciones pop y push de Array. Cuando nos encontramos con los caracteres '(', '[', '<', empujamos a la pila. Por otro lado, cuando encontramos ')', ']', '>', sacamos el último elemento de la pila. . Si no podemos encontrar los equivalentes de estos caracteres, determinamos que la cadena no es válida. Finalmente, si no quedan elementos en la pila, significa que la cadena es válida.
function verify(text) { let stack = []; for (const c of text) { if (c === '(' || c == '[' || c == '<') { stack.push(c); } else if (c === ')' || c == ']' || c == '>') { if (stack.length == 0) { return 0; } const popValue = stack.pop(); if (c === ')' && popValue != '(') { return 0; } else if (c === ']' && popValue != '[') { return 0; } else if (c === '>' && popValue != '<') { return 0; } } } if (stack.length > 0) { return 0; } return 1; }