Saltar al contenido

CódigoSin intentar

Prefijo común más largo

Dificultad: fácil

Devuelve el prefijo más largo compartido por todas las cadenas (cadena vacía si no hay ninguno).

Ver solución de referencia
// Start with the first word and cut letters off the end until every word starts with it.
export function longestCommonPrefix(strs: string[]): string {
if (strs.length === 0) return '';
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = prefix.slice(0, -1);
if (prefix === '') return '';
}
}
return prefix;
}
Cargando editor…