-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathleetcode-14-longestCommonPrefix.js
86 lines (74 loc) · 1.56 KB
/
leetcode-14-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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* @param {string[]} strs
* @return {string}
*/
// p: arr
// r: str / ''
// e:
// Input: strs = ["flower","flow","flight"]
// Output: "fl"
// flowera
// flowerb
// flowerc
// flowerd
// flow
//
var longestCommonPrefix = function (strs) {
let result = "";
let minLen = Infinity;
for (let s of strs) {
minLen = Math.min(minLen, s.length);
}
for (let i = 0; i < minLen; i++) {
for (let j = 1; j < strs.length; j++) {
if (strs[j - 1][i] !== strs[j][i]) return result;
}
result += strs[0][i];
}
return result;
};
// // max length of a word ?
// // O(arr.len x maxWord.len x maxWord.len)
// var longestCommonPrefix = function (strs) {
// const minLen = Math.min(...strs.map((s) => s.length));
// const map = {};
// for (let s of strs) {
// for (let i = 0; i <= minLen; i++) {
// map[s.slice(0, i)] = (map[s.slice(0, i)] || 0) + 1;
// }
// }
// console.log(map);
// let max = -Infinity;
// for (let m in map) {
// max = Math.max(max, map[m]);
// }
// let arr = [];
// for (let m in map) {
// if (map[m] === max) arr.push(m);
// }
// max = -Infinity;
// for (let a of arr) {
// max = Math.max(max, a.length);
// }
// for (let a of arr) {
// if (a.length === max) return a;
// }
// return "";
// };
// console.log(longestCommonPrefix(["flower", "flow", "flight"]));
// console.log(longestCommonPrefix(["a"]));
console.log(
longestCommonPrefix([
"flower",
"flowera",
"flowerb",
"flowerc",
"flowerd",
"flow",
])
);
// flowera
// flowerb
// flowerc
// flowerd
// flow