Minimum Deletions to Make Character Frequencies Unique
给一个字符串, 问删除多少个字符后, 能让所有的字符频率相同.
这个题主要是问删除几个, 而不是哪几个. 而且还只能删除.
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 |
class Solution { public int minDeletions(String s) { int[] f = new int[26]; for(char c : s.toCharArray()){ f[c - 'a']++; } Arrays.sort(f); int res = 0; Set<Integer> set = new HashSet<>(); for(int i = 0; i < 26; i++) { if(f[i] == 0) continue; if(!set.contains(f[i])) set.add(f[i]); else { while(set.contains(f[i])){ f[i]--; res++; } if(f[i] != 0) set.add(f[i]); } } return res; } } |