-
Notifications
You must be signed in to change notification settings - Fork 20
/
LongestCommonPrefix.js
53 lines (45 loc) · 1.06 KB
/
LongestCommonPrefix.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
/**
* Write a function to find the longest common prefix string amongst an array of strings.
*
* Accepted.
*/
/**
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function (strs) {
if (strs == null || strs.length === 0) {
return "";
}
if (strs.length === 1) {
return strs[0];
}
for (let i = 0; i < strs[0].length; i++) {
for (let j = 1; j < strs.length; j++) {
if (i === strs[j].length || strs[0].charAt(i) !== strs[j].charAt(i)) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
};
if (longestCommonPrefix([]).length === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (longestCommonPrefix(["abc"]) === "abc") {
console.log("pass")
} else {
console.error("failed")
}
if (longestCommonPrefix(["abcf", "abcd", "abcdefg"]) === "abc") {
console.log("pass")
} else {
console.error("failed")
}
if (longestCommonPrefix(["aa", "a"]) === "a") {
console.log("pass")
} else {
console.error("failed")
}