# 最长公共前缀

力扣🔗:https://leetcode-cn.com/problems/longest-common-prefix (opens new window)

# 题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

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

示例 2:

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

# 解题思路

  • 首先取出 strs 中第一个字符串作为参照字符串 first
  • 依次从 first 中取出每个字符 cur,记录该字符索引值为 pos
  • 每更新一次 cur, 将 curstrs 中除第一个字符串的所有字符串的 pos 位置字符进行对比,如不相同则得到结果为 first.slice(0, pos)

# 代码实现

/**
 * @param {string[]} strs
 * @return {string}
 */
function longestCommonPrefix(strs) {
  if (strs.length === 0) return ''
  if (strs.length === 1) return strs[0]


  let first = strs[0] // strs[0] 作为参照字符串
  let pos = 0
  let loop = 1
  let cur = first[pos] // 当前循环要参照对比的字符

  while (pos < first.length) {
    if (loop === strs.length) {
      // 每遍历完一次 strs,重置 loop 和更新 cur 
      loop = 1
      cur = first[++pos]
    }

    const str = strs[loop] // 当前遍历到的字符串
    if (!str) return ''
    if (str[pos] !== cur) {
      // 如果 str 中 pos 位置的字符与 cur 不相同,退出函数,并返回结果为 first 的子字符串
      return first.slice(0, pos)
    }

    loop++
  }

  return first
}