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