Longest Common Prefix

Jan 22, 2018

Write a function to find the longest common prefix string amongst an array of strings.

common prefix
function commonPrefix(strs) {
    var strA = strs.concat().sort();
    var a1 = strA[0], a2 = strA[strA.length-1], l = 0;
    for(var i=0; i <= a2.length; i++) {
        if(a1.charAt(i) === a2.charAt(i)) {
            l++;
        }
    }
    return a1.substring(0,l);
}

 

commonPrefix([‘sample’, ‘sampletext’, ‘samplecontent’]);    //  ‘sample’

commonPrefix([‘current’, ‘currenttag’, ‘curren’]);    //  ‘curren’

commonPrefix([‘become’, ‘because’, ‘before’]);    //  ‘be’