14. Longest Common Prefix

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

If there is no common prefix, return an empty string`""`.

Example 1:

Input: ["flower","flow","flight"]

Output: "fl"

Example 2:

Input: ["dog","racecar","car"]

Output: ""

Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters`a-z`.

 

var longestCommonPrefix = function(strs) {
    if(!strs.length) return '';
    var len = strs.reduce((pre,item)=>{
        return Math.min(pre,item.length);
    },Number.MAX_VALUE);

    var ans='';
    for(var i=0;i{
            return item[i] === a;
        });
        if(!f) break;
        ans += a;
    }
    return ans;
};

 

 

var longestCommonPrefix = function(strs) {
    if (!strs.length) return ""
    
    let baseWord = strs[0];
    for (let word = 1; word < strs.length; word++) {
        // currWord = String(strs[word])
        while (String(strs[word]).indexOf(baseWord) !== 0 && baseWord !== "") {
            baseWord = baseWord.substring(0, baseWord.length - 1)
        }
    }
    return baseWord;
};

 

 

var longestCommonPrefix = function(strs) {
     if (strs.length == 0) return "";
    let prefix = strs[0];
    for (let i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.slice(0, prefix.length - 1);
            if (prefix==="") return "";
        }        
    return prefix;
    
};

 

 

reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

reduce() 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(或者上次回调函数的返回值),当前元素值,当前索引,调用reduce的数组。

arr.reduce(callback,  [initialValue])

callback (执行数组中每个值的函数,包含四个参数)

- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))

- currentValue (数组中当前被处理的元素)

- index (当前元素在数组中的索引)

- array (调用 reduce 的数组)

initialValue (作为第一次调用 callback 的第一个参数)

 

var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(pre, cur, index, arr) {
    console.log(pre, cur, index);
    return pre + cur;
})
console.log(arr, sum);

14. Longest Common Prefix_第1张图片

你可能感兴趣的:(leetcode算法)