-
Notifications
You must be signed in to change notification settings - Fork 0
/
deleteTheLeastFrequentChar.ts
51 lines (37 loc) · 1.07 KB
/
deleteTheLeastFrequentChar.ts
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
//“ababac” —— “ababa”
//“aaabbbcceeff” —— “aaabbb”
const deleteTheLeastFrequentChar = (str: string): string => {
const charArr = str.split('');
const map = new Map<string, number>(); // O(n)
for (let i = 0; i < charArr.length; i++) { // O(n)
const curChar = charArr[i];
const count = map.get(curChar);
if (undefined === count) {
map.set(curChar, 1);
} else {
map.set(curChar, count + 1);
}
}
let min = Number.MAX_SAFE_INTEGER;
let minCharArr: string[] = [];
const mapArr = Array.from(map);
for (let i = 0; i < mapArr.length; i++) { //O(n)
const [char, count] = mapArr[i];
if (count < min) {
min = count;
minCharArr = [];
} else if (count === min) {
minCharArr.push(char);
}
}
const newCharArr: string[] = [];
for (let i = 0; i < charArr.length; i++) { //O(n2)
const temp = charArr[i];
if (minCharArr.includes(temp)) {
continue;
}
newCharArr.push(temp);
}
return newCharArr.join();
}
console.log(deleteTheLeastFrequentChar("ababac"));