-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
44 lines (38 loc) · 863 Bytes
/
res.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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-04-03 20:42:30
* @version $Id$
*
* Problem: Write a function to find the longest common prefix string amongst an array of strings.
*
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function(strs) {
if (strs === '' || strs.length === 0) {
return '';
}
let prefix = '',
strslen = strs.length,
strlen = strs[0].length;
for (let i = 0; i < strlen; i++) {
let jud = true;
for (let j = 1; j < strslen; j++) {
if (strs[j][i] === undefined || strs[j][i] !== strs[0][i]) {
jud = false;
break;
}
}
if (jud) {
prefix += strs[0][i];
} else {
return prefix;
}
}
return prefix;
};
/**
* Another solution: Sort the array first, and then you can simply compare the first and last elements in the sorted array.
*
*/