-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path014-Longest-Common-Prefix.js
More file actions
50 lines (40 loc) · 945 Bytes
/
014-Longest-Common-Prefix.js
File metadata and controls
50 lines (40 loc) · 945 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* https://leetcode.com/problems/longest-common-prefix/
* Difficulty:Easy
*
* Write a function to find the longest common prefix string amongst an array of strings.
*/
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
var m = strs.length;
if (!m) return '';
var min = Infinity;
var minIndex = -1;
for (var i = 0; i < strs.length; i++) {
if (strs[i].length < min) {
min = strs[i].length;
minIndex = i;
}
}
var s = strs[minIndex];
for (i = 0; i < s.length; i++) {
var ch = strs[0][i];
var same = true;
for (var j = 1; j < m; j++) {
if (strs[j][i] !== ch) {
same = false;
break;
}
}
if (!same) break;
}
return s.substr(0, i);
};
console.log(longestCommonPrefix([
'abdc',
'abc123',
'abc234'
]));