Toc
  1. Q:
    1. Example 1:
  • A:
  • Toc
    0 results found
    bbcfive
    Longest Common Prefix
    2019/06/21 Algorithm String

    Q:

    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.

    A:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    /**
    * @param {string[]} strs
    * @return {string}
    */
    var longestCommonPrefix = function(strs) {
    if (!strs.length) return '';
    if (strs.length == 1) return strs[0];

    var minest = 0;
    for (var i = 0; i < strs.length - 1; i++) {
    minest = Math.min(strs[i].length, strs[i+1].length);
    }

    var index = 0, longest = 0;
    while(index < minest) {
    for (var i = 0; i < strs.length - 1; i++) {

    if (strs[i][index] !== strs[i+1][index]) {
    longest = index;

    i = strs.length - 1
    index = minest
    } else {
    longest = index + 1;
    }
    }
    index++;
    }

    return strs[0].slice(0,longest);
    };
    本文作者:bbcfive
    版权声明:本文首发于bbcfive的博客,转载请注明出处!