forked from JackPu/JavaScript-Algorithm-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-common-prefix.js
More file actions
34 lines (31 loc) · 794 Bytes
/
longest-common-prefix.js
File metadata and controls
34 lines (31 loc) · 794 Bytes
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
// https://leetcode.com/problems/longest-common-prefix/description/
/**
* Write a function to find the longest common prefix string amongst an array of strings.
* input [] => '' ['abc', 'abe', 'abe'] => 'ab'
*/
const findLongestCommonPrefix = function (strs) {
if (strs.length === 0) {
return ''
}
const prefixMap = {}
let key = ''
var fn = function (str) {
for (let i = 0; i < strs.length; i++) {
if(strs[i].indexOf(str) !== 0) {
return false
}
}
return true
}
let j = 0
while(key !== strs[0]) {
const q = (key + strs[0][j++])
if (!fn(q)) {
break
}
key = q
}
return key;
}
console.log(findLongestCommonPrefix(["a","b"]))
module.exports = findLongestCommonPrefix