Skip to content

Instantly share code, notes, and snippets.

@acalpixca
Created March 3, 2018 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acalpixca/6d26f064f0d0c695dc6cdc1ef965fba2 to your computer and use it in GitHub Desktop.
Save acalpixca/6d26f064f0d0c695dc6cdc1ef965fba2 to your computer and use it in GitHub Desktop.
cassidoo challenge 26/02/2018
/*
Now, onto this week!
Given two strings, return if they have a common substring.
Bonus: Return the common substring(s).
Bonus x2: Do the original question plus the first bonus in less than O(n^2) time!
*/
function substringies(str1, str2) {
var substrings=[];
var minsublength=2; // challenge did not say what's the minimum substring length. I assume 2.
i=0;
while (i<str1.length){ // I don't want to use for here because we increase the i inside the inner loop.
j=0;
sub="";
while ((j<str2.length)&& (i<str1.length)){
if (str1[i]===str2[j]) { // coinciden las letras. La pongo en substring y preparo para comparar las letras siguientes
sub=sub+str1[i];
i++;
}
else { // no coinciden las letras
if ((sub.length>=minsublength)) {// si llevábamos un substring suficientemente largo, lo añadimos a la lista de resultados, y lo reseteamos
substrings.push(sub);
sub="";
}
else { // si no llevábamos un substring suficientemente largo, solo lo reseteamos
sub="";
}
}
j++;
if ((j>=str2.length) && (sub.length>=minsublength)){ // si hemos llegado al fin del 2º string y teníamos un substring suficientemente largo, lo añadimos y reseteamos
substrings.push(sub);
sub="";
}
}
i++;
}
return(substrings);
}
console.log(substringies("kkamoramarillo", "kkamericaeillo").toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment