精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/description/ 1647. Minimum Deletions to Make Character Frequencies Unique 給你一個字串,找出最少要從該字串刪除幾個字元才可以讓所有字母的數量都不同(數量0 不算)。 Example 1: Input: s = "aab" Output: 0 Explanation: s is already good. Example 2: Input: s = "aaabbbcc" Output: 2 Explanation: You can delete two 'b's resulting in the good string "aaabcc". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". Example 3: Input: s = "ceabaacb" Output: 2 Explanation: You can delete both 'c's resulting in the good string "eabaab". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). 思路: 1.先統計所有字母的數量。 2.嘗試把字母加入set,如果之前已經有這個數量的話就不斷的刪除字母並計數,直到 沒有出現過這個數量或全部字母都被刪除為止。 Java Code: -------------------------------------------------- class Solution { public int minDeletions(String s) { int[] count = new int[26]; for (char c : s.toCharArray()) { count[c - 'a']++; } Set<Integer> set = new HashSet<>(); int res = 0; for (int i = 0; i < 26; i++) { while (count[i] > 0 && !set.add(count[i])) { count[i]--; res++; } } return res; } } -------------------------------------------------- -- https://i.imgur.com/bFRiqA3.jpg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1694488044.A.231.html