-
Notifications
You must be signed in to change notification settings - Fork 181
/
39.longest-common-prefix.js
61 lines (47 loc) · 1.22 KB
/
39.longest-common-prefix.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 14. 最长公共前缀 https://leetcode-cn.com/problems/longest-common-prefix/
/**
* 14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
*
*/
// 横向扫描 也可以想起 版本比较的算法题,第一个和第二个比较,再拿结果和第三个比较
const longestCommonPrefix = (strs) => {
if (strs.length === 0) {
return ''
}
let prefix = strs[0]
const len = strs.length
const getPrevfix = (str1, str2) => {
if (str1.length > str2.length) {
return getPrevfix(str2, str1)
}
let i = 0
let substrLen = 0
const len = str1.length
while (i < len) {
if (str1[ i ] === str2[ i ]) {
substrLen++
} else {
break
}
i++
}
return str1.substr(0, substrLen)
}
for (let i = 1; i < len; i++) {
prefix = getPrevfix(prefix, strs[ i ])
if (prefix === '') {
return ''
}
}
return prefix
}
console.log(longestCommonPrefix(["flower","flow","flight"]))