-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_common_prefix.js
68 lines (54 loc) · 2.43 KB
/
longest_common_prefix.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* https://leetcode.com/problems/longest-common-prefix/submissions/
*
* 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 "".
*
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
const strsLen = strs.length
if (strsLen > 1) {
const arrayOfArrayOfStrings = strs.map(str => str.split(''))
const firstWord = arrayOfArrayOfStrings.splice(0, 1)[0]
// iterate through all of the other words. return the lowest index value the follows a matching string
const greatestIndex = arrayOfArrayOfStrings.reduce((acc, curr) => {
const matchingIdx = curr.map((letter, letterIdx) => firstWord[letterIdx] && letter === firstWord[letterIdx] ? true : false)
const falseIndex = (matchingIdx || []).findIndex(x => x === false)
const len = matchingIdx.length
// handles case where sub-string is entire word
if (falseIndex === -1 && len) {
if (matchingIdx[0] === true) {
// first word, set to len (meaning entire string matches the firstWord)
if (acc === null) {
return len
}
// means the current words failed index is less than another matching sub-strings index. Return this value
if (len < acc) {
return len
}
// means another matching sub-string is smaller
return acc
}
} else {
// first word, return the first index that does not match the sub-string
if (acc === null) {
return falseIndex
}
// means the current words failed index is less than another matching sub-strings index. Return this value
if (falseIndex < acc) {
return falseIndex
}
// means another matching sub-string is smaller
return acc
}
}, null)
return greatestIndex === null ? '' : firstWord.filter((x, i) => i < greatestIndex).join('')
}
return strsLen === 0 ? '' : strs[0]
};
longestCommonPrefix(["flower", "flow", "flight"]) // "fl"
longestCommonPrefix(["dog", "racecar", "car"]) // ""
longestCommonPrefix(["a"]) // "a"