• 【每日一练】20231023


    统计每个字符出现的次数相关问题

    方法一:map的put方法+遍历

    1. public class Test {
    2. public static void main(String[] args) {
    3. StringBuilder sb = new StringBuilder("");
    4. Random ran = new Random();
    5. for(int i=0;i<2000000;i++) {
    6. sb.append((char) ('a' + ran.nextInt(27)));
    7. }
    8. String str = sb.toString();
    9. //System.out.println(sb);
    10. //统计一下每个字符出现的次数?出现最多?
    11. Map map = new HashMap<>();
    12. long s = System.currentTimeMillis();
    13. for (int i = 0; i < str.length(); i++) {
    14. Character ch = str.charAt(i);
    15. if (Objects.isNull(map.get(ch))) {
    16. map.put(ch, 1);
    17. } else {
    18. map.put(ch, map.get(ch) + 1);
    19. }
    20. }
    21. long e = System.currentTimeMillis();
    22. System.out.println((e-s)+"ms");
    23. // System.out.println(map);
    24. }
    25. }

    方法二:用数组

    1. public class Test2 {
    2. public static void main(String[] args) {
    3. StringBuilder sb = new StringBuilder(""); //a-z
    4. Random ran = new Random();
    5. for(int i=0;i<2000000;i++) {
    6. sb.append((char) ('a' + ran.nextInt(26)));
    7. }
    8. String str = sb.toString();
    9. // System.out.println(str);
    10. int[] chs =new int[26]; //chs[0] chs[25] 0-a, 25-z
    11. long s = System.currentTimeMillis();
    12. for(int i =0; i
    13. char c = str.charAt(i); //if c is a
    14. chs[c-'a']+=1;
    15. }
    16. long e = System.currentTimeMillis();
    17. System.out.println((e-s)+"ms");
    18. //
    19. // for(int i=0;i
    20. // System.out.print((char)(i+'a')+",");
    21. // System.out.println(chs[i]);
    22. // }
    23. }
    24. }

    方法三:map的getOrDefault方法

    1. public class Test3 {
    2. public static void main(String[] args) {
    3. String str = "The so-called 'multifunctional' is not adding many elements, " +
    4. "but subtracting them. Only by leaving blank can ten thousand possibilities be created.";
    5. // 创建HashMap用于存储字母和出现次数
    6. Map countMap = new HashMap<>();
    7. // 遍历字符串的每个字符
    8. for (char c : str.toCharArray()) {
    9. // 判断是否为字母
    10. if (Character.isLetter(c)) {
    11. // 将字母转为小写形式
    12. char lowercase = Character.toLowerCase(c);
    13. // 更新字母的出现次数,使用Map的getOrDefault方法来获取该字母已有的计数并加一
    14. countMap.put(lowercase, countMap.getOrDefault(lowercase, 0) + 1);
    15. }
    16. }
    17. // 遍历Map输出每个字母及其出现次数
    18. for (char c : countMap.keySet()) {
    19. int count = countMap.get(c);
    20. System.out.println(c + ": " + count);
    21. }
    22. }
    23. }

  • 相关阅读:
    java计算机毕业设计客服管理系统源码+mysql数据库+系统+lw文档+部署
    PROSS程序设计
    Windows11下清理Docker Desktop与wsl的C盘空间占用
    ctfshow web七夕杯
    Hive 使用达梦DM8 无法识别 “COMMENT” 问题
    Springboot实现jwt的token验证(超简单)
    Python Flask
    linux中利用VScode编写C++程序
    Anaconda搭建环境(tensorflow+pytorch)
    《FFmpeg Basics》中文版-05-裁剪视频
  • 原文地址:https://blog.csdn.net/m0_62006803/article/details/133998435