Created
December 28, 2017 16:20
-
-
Save aprilmintacpineda/039a09468b67bfcedb9c15ff99a76a5a to your computer and use it in GitHub Desktop.
Longest Common Substring & longest consecutive substring javascript implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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