• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Microsoft OA

Given a string S consisting of N lowercase letters, return the minimum number of letters that must be deleted to obtain a word in which every letter occurs a unique number of times

没有想到要再存一个HashMap, appearance to character mapping

 1 package UniqueCharacter;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 public class Solution {
 7     public static int charCountToDelete(String s) {
 8         HashMap<Character, Integer> map = new HashMap<>();
 9         for (char c : s.toCharArray()) {
10             map.put(c, map.getOrDefault(c, 0) + 1);
11         }
12 
13         int res = 0;
14         HashMap<Integer, Character> intToCharMap = new HashMap<>();
15         for (Map.Entry<Character, Integer> entry : map.entrySet()) {
16             int value = entry.getValue();
17             while (intToCharMap.containsKey(value)) {
18                 res ++; // need to delete
19                 value --;
20             }
21             intToCharMap.put(value, entry.getKey());
22         }
23         return res;
24     }
25 
26     public static void main(String[] args) {
27         int res = charCountToDelete("aaaabbbbcccdde");
28         System.out.printf("result is %d\n", res);
29         int res2 = charCountToDelete("aaaabbbb");
30         System.out.printf("result is %d\n", res2);
31         int res3 = charCountToDelete("aaaabbbccd");
32         System.out.printf("result is %d\n", res3);
33     }
34 }

 

posted @ 2019-10-14 08:34  neverlandly  阅读(515)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3