-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-009-mostFrequentChar-2.js
76 lines (61 loc) · 1.36 KB
/
structy-009-mostFrequentChar-2.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
// p: str
// r: str
// O(s.length)
const mostFrequentChar = (s) => {
// todo
const map = {};
for (let c of s) {
map[c] = (map[c] || 0) + 1;
}
// let max = -Infinity;
// let result = "";
// for (let c of s) {
// if (map[c] > max) {
// result = c;
// max = map[c];
// }
// }
let result = null;
for (let c of s) {
if (result === null || map[c] > map[result]) {
result = c;
}
}
return result;
};
// const mostFrequentChar = (s) => {
// // todo
// const map = {};
// for (let c of s) {
// map[c] = (map[c] || 0) + 1;
// }
// let max = -Infinity;
// for (let c in map) {
// max = Math.max(map[c], max);
// }
// for (let c of s) {
// if (map[c] === max) return c;
// }
// };
console.log(mostFrequentChar("bookeeper")); // -> 'e'
// // too many lines
// const mostFrequentChar = (s) => {
// // todo
// const map = {};
// for (let c of s) {
// map[c] = (map[c] || 0) + 1;
// }
// let max = -Infinity;
// for (let c in map) {
// max = Math.max(map[c], max);
// }
// const allMax = [];
// for (let c in map) {
// map[c] === max && allMax.push(c);
// }
// for (let i = 0; i < allMax.length; i++) {
// allMax[i] = s.indexOf(allMax[i]);
// }
// let min = Math.min(...allMax);
// return s[min];
// };