File tree 1 file changed +16
-16
lines changed
1 file changed +16
-16
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int minDeletions (String s ) {
3
- int [] frequencies = new int [26 ];
3
+ int [] frequency = new int [26 ];
4
4
for (char c : s .toCharArray ()) {
5
- frequencies [c - 'a' ]++;
5
+ frequency [c - 'a' ]++;
6
6
}
7
- Arrays .sort (frequencies );
8
- int expectedFrequency = frequencies [25 ];
9
- int numOfDeletions = 0 ;
10
- for (int i = 25 ; i >= 0 ; i --) {
11
- if (frequencies [i ] == 0 ) {
12
- break ;
13
- }
14
- if (frequencies [i ] > expectedFrequency ) {
15
- numOfDeletions += frequencies [i ] - expectedFrequency ;
16
- } else {
17
- expectedFrequency = frequencies [i ];
7
+ PriorityQueue <Integer > pq = new PriorityQueue <>(Collections .reverseOrder ());
8
+ for (int freq : frequency ) {
9
+ if (freq > 0 ) {
10
+ pq .add (freq );
18
11
}
19
- if (expectedFrequency > 0 ) {
20
- expectedFrequency --;
12
+ }
13
+ int numOfDeletions = 0 ;
14
+ while (!pq .isEmpty ()) {
15
+ int removedFreq = pq .poll ();
16
+ if (!pq .isEmpty () && pq .peek () == removedFreq ) {
17
+ numOfDeletions ++;
18
+ if (removedFreq > 1 ) {
19
+ pq .add (removedFreq - 1 );
20
+ }
21
21
}
22
22
}
23
23
return numOfDeletions ;
24
- }
24
+ }
25
25
}
You can’t perform that action at this time.
0 commit comments