[Java] Find the most frequently occurring character in a string

1. Do not use containers

/**
 * 方法一 :不使用容器
 * 思路:
 * 首先将字符串转换成数组,然后建立两个数组,一个属于 26 字符表,一个用于保存表中各个字符出现的次数,最后遍历该数组,找到该数组中最大的数与位置,即为出现最多的字符与出现次数。
 */
public void function1(){
    
    

    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    char[] ch = str.toCharArray();
    char[] m = {
    
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    int[] num = new int[26];
    for (int i = 0; i < ch.length; i++) {
    
    
        for (int j = 0; j < 26; j++) {
    
    
            if (ch[i] == m[j])
                num[j]++;
        }
    }

    int maxCount = 0, temp = 0;  // maxCount 字符出现的最大次数,temp 最大字符的位置
    for (int i = 0; i < 26; i++) {
    
    
        if (num[i] > maxCount){
    
    
            maxCount = num[i];
            temp = i;
        }
    }
    System.out.println(m[temp] + "是出现最多的字符,次数:"+ maxCount);

}

2. Use the container

/**
 * 方法二:使用容器
 * 思路:
 * 使用 Map,先将字符串转换为字符数组,然后将字符数组加到 Map 中,当存在相同的字符时将对应的 value++,最后获取 Map 中 value 的最大值。
 */
public void function2() {
    
    
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    char[] ch = str.toCharArray();

    // 将字符串保存到 Map
    Map<Character, Integer> map = new HashMap<Character, Integer>();
    for (int i = 0; i < ch.length; i++) {
    
    
        if (map.get(ch[i]) != null) {
    
    
            map.put(ch[i], map.get(ch[i]) + 1);
        } else {
    
    
            map.put(ch[i], 1);
        }
    }

    // 获取 Map 中 value 的 Max
    // 迭代器遍历 Map
    Iterator iterator = map.keySet().iterator();
    char maxChar = 'a';     // 最大的字符
    int maxCount = 0;            // 最大的字符出现的次数
    while (iterator.hasNext()) {
    
    
        Character character = (Character) iterator.next();
        if (maxCount < map.get(character)) {
    
    
            maxCount = map.get(character);
            maxChar = character;
        }
    }

    System.out.println(maxChar + "是出现次数最多的字符,次数是:" + maxCount);
}

Guess you like

Origin blog.csdn.net/qq_33833327/article/details/129626055
Recommended