最长公共前缀

二分查找

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    if(strs === null || strs.length === 0) return "";

    var minLen = Number.MAX_SAFE_INTEGER;
    for (var v of strs) {
        minLen = Math.min(minLen, v.length)
    }

    var low = 1,
        high = minLen;
    while (low <= high) {
        var middle = (low + high) >> 1;
        if(isCommonPrefix(strs, middle)) {
            low = middle + 1
        } else {
            high = middle - 1
        }
    }
    
    return strs[0].substring(0, (low + high) >> 1);
};


var isCommonPrefix = function(strs, len) {
    var str1 = strs[0].substring(0, len);
    for(let i = 0;i<strs.length;i++) 
        if (!strs[i].startsWith(str1))
            return false;
    return true;
}

推荐阅读更多精彩内容