字符串中出现次数最多的字符
2023-06-16 10:17:39
ts
const str = 'ababajshbaasdaaaa'
// { char:'a', count:9 }
function computeString(str) {
const compute = {}
for (let i = 0; i < str.length; i++) {
let key = str[i]
if (compute[key]) {
compute[key] = compute[key] + 1
} else {
compute[key] = 1
}
}
let max
Object.values(compute).forEach(item => {
if (max) {
if (max < item) {
max = item
}
} else {
max = item
}
})
let char
for (const item in compute) {
if (compute[item] == max) {
char = item
}
}
return { char, count: max }
}
console.log(computeString(str))
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
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