LeetCode-14. Longest Common Prefix

问题描述

rite 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
2
Input: strs = ["flower","flow","flight"]
Output: "fl"

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

解答

方法一:横向扫描
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
/*
* @Description: 14. Longest Common Prefix
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @description: 方法一:横向扫描
* @param {string[]} strs
* @return {string}
*/
const longestCommonPrefix = function (strs) {
const prefixOfTwo = (str1, str2) => {
const len = Math.min(str1.length, str2.length)
let index = 0
while (index < len && str1[index] === str2[index]) {
index++
}
return str1.substring(0, index)
}

let prefix = strs[0]
for (let i = 1; i < strs.length; i++) {
prefix = prefixOfTwo(prefix, strs[i])
}
return prefix
}
方法二:纵向扫描
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
* @Description: 14. Longest Common Prefix
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @description: 方法二:纵向扫描
* @param {string[]} strs
* @return {string}
*/
const longestCommonPrefix = function (strs) {
const len = strs.length
const count = strs[0].length

for (let i = 0; i < count; i++) {
let first = strs[0][i]
for (let j = 1; j < len; j++) {
if (strs[j][i] !== first || i === strs[j].length) {
return strs[0].substring(0, i)
}
}
}
return strs[0]
}