Skip to content

Instantly share code, notes, and snippets.

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 aprilmintacpineda/039a09468b67bfcedb9c15ff99a76a5a to your computer and use it in GitHub Desktop.
Save aprilmintacpineda/039a09468b67bfcedb9c15ff99a76a5a to your computer and use it in GitHub Desktop.
Longest Common Substring & longest consecutive substring javascript implementation.
function longestConsecutiveSubstr(str) {
var longestConsecutiveSubstr = '';
var leftOff = 1;
for (var a = 0; a < str.length - 1; a = leftOff) {
var newLongestConsecutiveSubstr = '';
for (var b = a + 1; b < str.length; b++) {
if (str[a] == str[b]) {
newLongestConsecutiveSubstr += str[a];
if (b == a + 1) {
newLongestConsecutiveSubstr += str[a];
}
} else {
break;
}
}
if (newLongestConsecutiveSubstr.length > longestConsecutiveSubstr.length) {
longestConsecutiveSubstr = newLongestConsecutiveSubstr;
}
leftOff = b;
}
return longestConsecutiveSubstr;
}
function longestCommonSubstring() {
var longestConsecutiveSubstrs = [];
var assertions = [];
for (var a = 0; a < arguments.length; a++) {
longestConsecutiveSubstrs.push(longestConsecutiveSubstr(arguments[a]));
}
for (a = 0; a < arguments.length; a++) {
for (var b = a + 1; b < arguments.length; b++) {
if (longestConsecutiveSubstrs[a] == longestConsecutiveSubstrs[b]) {
assertions.push({
strings: [arguments[a], arguments[b]],
common: longestConsecutiveSubstrs[a]
});
} else {
assertions.push({
strings: [arguments[a], arguments[b]],
common: null
});
}
}
}
return assertions;
}
console.log(longestCommonSubstring('airproof', 'door', 'room'));
console.log('tesssssssst', longestConsecutiveSubstr('tesssssssst'));
console.log('tessssssssttttttttttttt', longestConsecutiveSubstr('tessssssssttttttttttttt'));
console.log('teeeeeeeeeeeeeeesssssssstttttt', longestConsecutiveSubstr('teeeeeeeeeeeeeeesssssssstttttt'));
// console.log(longestConsecutiveSubstr('airproof'));
// console.log(longestConsecutiveSubstr('door'));
// console.log(longestConsecutiveSubstr('room'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment