华为机试 统计字符串中最长的数字串及统计字符串中字母出现最多的次数

2023-11-18

不多说,上代码:
package com.it.thread;

import java.util.*;

public class SoftTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
// selectNum(str);
chartCount(str);
}

/**
 * 进行字符串中字符的统计
 *
 * @param str
 */
public static void chartCount(String str) {
    HashMap<Character, Integer> chartMap = new HashMap();

    for (int i = 0; i < str.length(); i++) {
        Character key = str.charAt(i);
        if (!chartMap.containsKey(key)) {
            chartMap.put(key, 1);
        } else {
            int newValue = chartMap.get(key) + 1;
            chartMap.put(key, newValue);
        }
    }
    /**
     * 用于遍历输出字母统计结果
     */
    for (Map.Entry<Character, Integer> entry : chartMap.entrySet()) {
        Character k = entry.getKey();
        Integer v = entry.getValue();
        System.out.println(k + ":" + v);
    }
    /**
     * 用于找到出现最多的次数
     */
    int[] arr = new int[chartMap.size()];
    int max = arr[0];//用来存放出现最多的次数
    List<Character> chars = new ArrayList<>();//用来存放出现次数最多的字母

    for (Integer numValue : chartMap.values()) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = numValue;
            for (int j = 0; j < arr.length; j++) {
                if (arr[j] > max)
                    max = arr[j];
            }
        }
    }
    /**
     * 用于找出最多次数对应字符集合
     */
    for (Character tmp : chartMap.keySet()) {
        Integer v = chartMap.get(tmp);
        if (v == max) {
            chars.add(tmp);
        }
    }
    System.out.println("出现次数最多的字母次数是 " + max);
    System.out.println(" 出现次数最多的字母是: " + chars);

}

/**
 * 本方法返回一个字符串中最长的数字串及其长度
 *
 * @param str String
 */
public static void selectNum(String str) {
    // String tmp = str.replaceAll("[^0-9]", " ");
    String tmp = str.replaceAll("\\D", " ");
    String[] arr = tmp.split(" ");
    // System.out.println("tmp = " + tmp);
    String max = null;
    for (int i = 0; i < arr.length; i++) {
        max = arr[0];
        for (int j = 1; j < arr.length; j++) {
            if (max.length() < arr[j].length()) {
                max = arr[j];
            }
        }
    }
    System.out.println("最长的数字串为:" + max + "长度为:" + max.length());
}

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

华为机试 统计字符串中最长的数字串及统计字符串中字母出现最多的次数 的相关文章

随机推荐