Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
Encontrar subcadena en cadena

Estoy tratando de encontrar la subcadena en una cadena usando la complejidad O (N). El siguiente es el código que he escrito. Devuelve indefinido y no sé por qué. Por favor, hágame saber qué está fallando en mi código.

 let omg = "omg"; let omgi = "omjiklmonomgib"; function stringSearch(smallString, bigString) { let left = 0; let right = left+(smallString.length - 1); while (left > right) { if (smallString[left] === bigString[left]) { if (smallString[right] === bigString[right]) { left++; right--; if (left === right) { if (smallString[right] === bigString[left]) { return true; } else if (right === left + 1) { if (smallString[right] === bigString[right] && smallString[left] === bigString[left]) { return true; } else { left = right + 1; right = left + (smallString.length - 1); } } } } } } } console.log(stringSearch(omg, omgi)); //Undefined

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Por lo que entiendo, solo estás rehaciendo String.prototype.match . Intente verificar esto, ya que probablemente sería una forma más fácil de hacer lo que está diciendo. Lo siento, me perdí la parte de la complejidad O(N).

Si realmente quieres hacer uno personalizado, puedo darte algunos consejos.
En primer lugar, debe tener una variable de "caché" (una para todas, no left y right ) y otra variable que se found (será un booleano, así que configúrelo en falso). La variable "caché" almacenará el texto, y la otra almacenará si encontró la smallString .

Básicamente, recorre cada carácter y almacena los caracteres de smallString , sin embargo, largos en la variable "caché". Una vez que la variable "caché" tenga la misma longitud que smallString , ejecute una instrucción if en ella. Si no es igual a smallString , elimine el primer carácter del "caché". La próxima iteración en el ciclo, agregará otro carácter. Luego hace lo mismo que antes, ejecuta una instrucción if y, si no es igual, elimina el primer carácter y continúa el ciclo hasta que lo encuentre, o la cadena termine. Si lo encontró, establezca el valor booleano en verdadero.

Algo como esto:

 function stringSearch(smallString, bigString, caseSensitive=true) { if(!caseSensitive) { // if caseSensitive is false, make everything lower case smallString = smallString.toLowerCase(); bigString = bigString.toLowerCase(); } let cache = ""; // string cache let found = false; // result for(i=0;i<bigString.length;i++) { // loop through every character in bigString cache+=bigString[i]; // add the current character to the cache if(cache.length == smallString.length) { // check if the cache's length is the same as the smallString's length if(cache == smallString) { // check if the cache is equal to the smallString found = true; // set found to true break; // break the loop (stop it from going on) } else { cache = cache.substring(1); // set cache to itself but remove the first character } } } return found; // return result } // example: console.log("String 'hello, world' has 'hello': "+stringSearch("hello", "hello, world")); console.log("String 'HELLO WORLD' has 'hello': "+stringSearch("hello", "HELLO WORLD")); console.log("String 'HELLO WORLD' has 'hello' (not case sensitive): "+stringSearch("hello", "HELLO WORLD", false)); console.log("String 'hey hi hello WORLD' has 'hello': "+stringSearch("hello", "hey hi hello WORLD")); console.log("String 'hey hi hello' has 'hello': "+stringSearch("hello", "hey hi hello")); console.log("String 'hey lol o' has 'hello': "+stringSearch("hello", "hey lol o"));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Veo un par de problemas. Primero, el código no tiene una declaración de retorno para cada rama lógica. Quiero decir que, para cada condición en una declaración if, then, else, el código debe tener una declaración de devolución o algún tipo de declaración de flujo de control (por ejemplo, una llamada recursiva o continuar) que eventualmente conducirá a una declaración de devolución.

El segundo problema es el ciclo while . Supuestamente, right debería ser mayor que left desde el comienzo de la función (a menos que la longitud de smallString sea 0) porque right es la longitud de smallerString menos 1. La condición while es left > right , por lo que no se ejecutará nada dentro de while a menos que smallString tenga una longitud negativa (que no la tiene).

Por cierto, si desea verificar bigString completo, deberá iterar sobre bigString , no smallString . Si solo está verificando los caracteres smallString.length , no verificará todo el bigString . Averiguar cómo escribir esta función es un buen ejercicio, por lo que le dejaré escribirla a usted y me abstendré de proporcionar una implementación yo mismo. ¡Sigan con el buen trabajo!

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda