Sollicitatievraag bij Infrrd

Write a JavaScript program to find the longest common substring(LCS) and its length. Ex: Two strings i.e "Outputname" and "Yourname" were given and the longest common substring i.e "name" should be the o/p.

Antwoord op sollicitatievraag

Anoniem

25 sep 2019

function longestCommonSubstring(str1, str2){ if (!str1 || !str2) return { length: 0, sequence: "", offset: 0 }; var sequence = "", str1Length = str1.length, str2Length = str2.length, num = new Array(str1Length), maxlen = 0, lastSubsBegin = 0; for (var i = 0; i maxlen) { maxlen = num[i][j]; thisSubsBegin = i - num[i][j] + 1; if (lastSubsBegin === thisSubsBegin) {//if the current LCS is the same as the last time this block ran sequence += str1[i]; } else //this block resets the string builder if a different LCS is found { lastSubsBegin = thisSubsBegin; sequence= ""; //clear it sequence += str1.substr(lastSubsBegin, (i + 1) - lastSubsBegin); } } } } } return { // length: maxlen, sequence, // offset: thisSubsBegin }; }