Problem Description

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

If no common prefix exists, the empty string "" is returned.

Example 1:

 输入:strs = ["flower","flow","flight"]
输出:"fl"

Example 2:

 输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
Likou original title address: https://leetcode.cn/problems/longest-common-prefix

solution

Thought analysis

  • For such a topic, we must first exclude special cases, such as there is only one item in the array. If there is only one item, this item is the longest common prefix. So judge alone length是否等于1
  • Naturally it is a common prefix, then we can take the word of the string to judge whether the current word is followed by 每一项 , so we will be quite 数组的every方法
  • Since it is a public prefix, that is, the prefix corresponding to the beginning of the string, we will think of 字符串的startsWith方法
  • For example, the array is: ['abc','abcd','abcde'] . We directly use the first item as the benchmark, get the first word of the first item, a , and then look at this a is it not that every subsequent item also starts a beginning. If so, take one digit from the back (here, it should be spliced into ab ), and then look back to see if each item starts with ab .
  • This cycle continues until one of the items does not match the one starting with ab . When a certain condition is not met, exit the loop and we will while循环

code show as below

 // 额外抽离出一个函数,用于判断
function startFn(strs, s) {
    let flag = strs.every((item) => {
        if (item.startsWith(s)) { // 必须每一项都要符合以xxx开头,才返回true
            return true
        }
    })
    return flag
}

var longestCommonPrefix = function (strs) {
    // 如果数组只有一项,那么最长公共前缀就是自身
    if (strs.length == 1) {
        return strs[0]
    }
    // 如果数组有多项,就要去遍历对比
    if (strs.length >= 2) {
        // 如果数组中第一项是空字符串的,那么所有的公共前缀就是空字符串
        // 这里需要注意空字符串没有第0项即: ""[0] === undefined
        if (!strs[0][0]) {
            return ''
        }
        // 排除空字符串的情况,我们在正常遍历即可
        let i = 0 // 这里的i是为了让第一项的单词累加
        let s = strs[0][i]
        while (startFn(strs, s)) {
            i = i + 1
            if (i > strs[0].length - 1) {
                // while内部的return说明已经全部循环完了(每一项长得都一样)
                return s
            } else {
                s = s + strs[0][i]
            }
        }
        // while外部的循环说明到某一个单词的时候,别的单词没有,即没有更大的最长公共前缀了
        return s.slice(0, -1) // 注意这里需要截取一下,多了一个单词。因为上方的s = s + strs[0][i] 多加了一次
    }

};

The performance can also be screenshotted as follows

Summarize

For such a similar topic, first exclude some special cases, and then in the process of thinking, think about which method APIs we can use, and finally follow the ideas. After submitting, if it fails, analyze the reasons for the failure and optimize the code.


水冗水孚
1.1k 声望589 粉丝

每一个不曾起舞的日子,都是对生命的辜负