-
Notifications
You must be signed in to change notification settings - Fork 15
/
LongestCommonPrefix.js
51 lines (48 loc) · 1.4 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
/**
* @author Anirudh Sharma
*
* Write a function to find the longest common prefix string amongst an array of strings.
*
* If there is no common prefix, return an empty string "".
*
* Constraints:
*
* 0 <= strs.length <= 200
* 0 <= strs[i].length <= 200
* strs[i] consists of only lower-case English letters.
*/
const longestCommonPrefix = (strings) => {
// This variable will store the longest common prefix
let lcp = "";
// Special cases
if (strings === undefined || strings.length === 0) {
return lcp;
}
// Find the length of the shortest string from
// the array of strings
let minLength = strings[0].length;
for (let i = 1; i < strings.length; i++) {
minLength = Math.min(minLength, strings[i].length);
}
// Loop until the minimum length
for (let i = 0; i < minLength; i++) {
// Get the current character from first string
let current = strings[0].charAt(i);
// Check if this character lies in every string
// or not
for (let s of strings) {
if (s.charAt(i) !== current) {
return lcp;
}
}
lcp += current;
}
return lcp;
};
const main = () => {
let strings = ["flower", "flow", "flight"];
console.log(longestCommonPrefix(strings));
strings = ["dog", "racecar", "car"];
console.log(longestCommonPrefix(strings));
};
main();