Skip to content

Instantly share code, notes, and snippets.

@ShaakhDev
Created May 31, 2022 14:54
Show Gist options
  • Save ShaakhDev/daff21a9ae8aba390c7ff78555967b56 to your computer and use it in GitHub Desktop.
Save ShaakhDev/daff21a9ae8aba390c7ff78555967b56 to your computer and use it in GitHub Desktop.
Finding the longest common substring in the array of strings.
let a = process.argv.slice(2);
String.prototype.strstr = function (search) {
var position = this.indexOf(search);
if (position == -1) {
// not found
return '';
}
return this.slice(position);
};
function longestCommonSubstring(words) {
var wordsSorted = words.sort((a, b) => a.length - b.length);
var longest_substring = []
var shortest_string = wordsSorted.shift().split('');
while (shortest_string.length) {
longest_substring.unshift('');
dance:
for (i = 0; i < shortest_string.length; i++) {
for (j = 0; j < wordsSorted.length; j++) {
if (!wordsSorted[j].strstr(longest_substring[0] + shortest_string[i])) {
break dance;
}
}
longest_substring[0] += shortest_string[i];
}
shortest_string.shift();
}
let sorted = longest_substring.sort((a, b) => a.length - b.length);
return sorted.pop();
}
let res = longestCommonSubstring(a);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment