JS solution


  • 0
    const longestInTwo = (a, b) => {
        let long, short;
        if (a.length > b.length) {
            long = a;
            short = b;
        } else {
            long = b;
            short = a;
        }
        while (long.indexOf(short) !== 0) {
            short = short.slice(0, -1);
        }
        return short;
    };
     
    var longestCommonPrefix = function(strs) {
        if (strs.length === 0) return '';
        return strs.reduce((result, s) => {
            return longestInTwo(result, s);
        });
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.