Programming problem: Find two strings of the longest common substring Javascript function

This is a multi-network benefits the tip of a pen questions, here's what it had to Tucao written system is really rubbish, do question the system with habits of cattle off the network, represents the written test done very uncomfortable.

Here to share my approach

Ideas: pass two strings to compare who who long short, short traversal strings, two for loops, the maximum length of the outer loop from traversing the length decreasing one by one, left most inner circle from the short string if the maximum length of the string interception started, check, taken over a long string inside the string until it finds a matching character string

Code:

function findLongestCommonStr (s1, s2) {
     var commonStr = '', s1.length = Ll, L2 of = s2.length;
     // compare s1, s2 of length, who see who long short 
    var shortStr = Ll> L2 of? s2: S1 ;
     var LongStr = Ll> L2 of? S1: S2;
     // shorter string 
    var strLen = shortStr.length;

    // iterate short string, descending down 
    for (the let J = strLen; J> 0; J, ) {
         // different lengths possible total of i, traversing from the right to do 
        for (the let i 0 =; I <= strLen - J; I ++ ) {
             // the cut out part of a string of short string 
            commonStr = shortStr.substr (I, J);
             // to facilitate observations during operation, the print will look much intuitive 
            the console.log ( 'commonStr:', commonStr, 'I:', I, 'J:' , J);

            // put in long strings to see if there is no match, if there is a direct return 
            IF (longStr.indexOf (commonStr)> = 0) return commonStr
        }
    }
    // If not, return an empty string 
    return ''
}

console.log(findLongestCommonStr("qwer--", "qtrrwqw-")); //qw

// results following the printing, the process functions performed, i is taken from the start where, j is a length taken 
@ commonStr: qwer-- I: J 0:. 6 
@ commonStr: qwer- I: J 0:. 5 
// commonStr: wer-- I: J. 1:. 5 
// commonStr: qwer I: J 0:. 4 
// commonStr: wer- I: J. 1:. 4 
// commonStr: er-- I: J 2:. 4 
/ / commonStr: QWE I: J 0:. 3 
// commonStr: WER I: J. 1:. 3 
// commonStr: ER- I: J 2:. 3 
// commonStr: r-- I: J. 3:. 3 
// commonStr: qw i: 0 j: 2

 

Guess you like

Origin www.cnblogs.com/linxf/p/12636955.html