java笔试题(二)


import java.util.ArrayList;
import java.util.Scanner;

public class Javatest76 {
    /**
     * 笔试题
     * 练习2:输入一个字符串,输出出现次数最多的前2个字符及出现次数
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String s = sc.nextLine();
        test(s);
    }
    //统计字符串中每个字符出现次数
    public static void test(String s){
        char[] arr = s.toCharArray();
        ArrayList list = new ArrayList<>();
        int[] count = new int[26];
        //出现次数最多的两个字母出现的次数
        int max1 = 0;
        int max2 = 0;
        //出现次数最多的两个字符
        char max1c = 'a';
        char max2c = 'a';
        //统计字符串中每个字符出现的次数
        for (int i = 0; i < arr.length; i++) {
            if(!list.contains(arr[i])){
                //记录字符出现的顺序
                list.add(arr[i]);
            }
            count[arr[i] - 'a']++;
            //出现次数多于当前最多的次数
            if(count[arr[i] - 'a'] >= max1){
                if(arr[i] != max1c){
                    max2 = max1;
                    max2c = max1c;
                    max1c = arr[i];
                }
                max1 = count[arr[i] - 'a'];
            }
            //出现次数多于当前出现次数第二多的
            else if(count[arr[i] - 'a'] > max2){
                max2 = count[arr[i] - 'a'];
                max2c = arr[i];

            }
        }
        //出现次数最多的多余两个字符时,控制仅输出前两个
        int time = 0;
        for (int i = 0; i < list.size(); i++) {
            if((count[list.get(i) - 'a'] == max1 || count[list.get(i) - 'a'] == max2) && time < 2){
                System.out.println(list.get(i) + "出现次数:" + count[list.get(i) - 'a']);
                time++;
            }
        }

    }
}