-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.longest.prefix1.js
More file actions
38 lines (34 loc) · 915 Bytes
/
string.longest.prefix1.js
File metadata and controls
38 lines (34 loc) · 915 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
/*
* @title: Longest Common Prefix
* @description: longest common prefix in array of words
* @author: Thorsten Kober
* @email: [email protected]
*/
function getMinLength(arr) {
let min = arr[0].length;
for (let i = 1; i < arr.length; i++) {
if (arr[i].length < min) {
min = arr[i].length;
}
}
return min;
}
function getPrefix(arr) {
const minLength = getMinLength(arr);
const result = [];
for (let i = 0; i < minLength; i++) {
const current = arr[0][i];
for (let j = 1; j < arr.length; j++) {
if (arr[j][i] !== current) {
return result.join('');
}
}
result.push(current);
}
return result.join('');
}
// npx jest algorithms/string/string.longest.prefix1.js
test('getPrefix()', () => {
expect(getPrefix(['geeksforgeeks', 'geeks', 'geek', 'geezer'])).toEqual('gee');
expect(getPrefix(['apple', 'ape', 'april'])).toEqual('ap');
});