-
Notifications
You must be signed in to change notification settings - Fork 344
/
最长公共前缀.js
41 lines (37 loc) · 871 Bytes
/
最长公共前缀.js
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
32
33
34
35
36
37
38
39
40
41
/**
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function (strs) {
let point = 0
let common = ""
let shortestStr
let getShortestStr = false
if (strs.length === 1) {
return strs[0]
}
if (strs.length === 0) {
return ''
}
while (1) {
for (let i = 0; i < strs.length; i++) {
let str = strs[i]
if (i > 0 && str[point] !== strs[i - 1][point]) {
return common
}
// 寻找最短的字符串
if (!getShortestStr) {
if (!shortestStr) {
shortestStr = str
} else if (str.length < shortestStr.length) {
shortestStr = str
}
}
}
common += strs[0][point] || ''
point++
if (point > shortestStr.length) {
return common
}
}
}