最长公共前缀

二分查找

/**
 * @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

你可能感兴趣的:(最长公共前缀)