Find the largest number of characters in a string appears, if the same characters appear multiple times, then find out the character first appeared

Topic Description: Find the highest number of characters appear in a string, if there are multiple occurrences of the same character, that character would find the first occurrence of
thinking:

My first reaction was three steps:

  1. Traversing the string, the number of statistics for each character appears
  2. Find the maximum number of
  3. The maximum number of characters that identify the corresponding

这样解决是没有问题的,但是太笨了,遍历了三次。经过思考,发现可以利用map的特性,只需要遍历一次就可以解决问题,贴上代码如下:

/**
 * 找出一个字符串中出现次数最多的字符,如果有多个出现次数相同的字符,就找出最先出现的那个。
 */
public class FirstChar {
    /**
     * 使用倒序查找的方式找到首先出现的次数最多的那个字符
     * @param str
     * @return
     */
    private static char searchFirstChar(String str) {
        // 定义一个map,根据键值的唯一性,使用字符串中的字符作为键,出现的次数作为值
        Map<Character, Integer> map = new HashMap<>();
        // 将字符串转化为字符数组
        char[] ch = str.toCharArray();
        // 定义一个最大次数,初始值为0
        int max = 0;
        // 定义出现次数最多的字符,初始值为第一个字符
        char ret = ch[0];
        // 倒叙遍历字符串数组
        for (int i = ch.length - 1; i >= 0; i--) {
            // 如果map中存在该字符,则将map中的value加1,也就是字符出现的次数加1,
            // 否则就设置当前字符出现的次数为1
            if (map.containsKey(ch[i])) {
                // 将该字符出现的次数加1
                map.put(ch[i], map.get(ch[i]) + 1);
                // 如果该字符出现的次数大于max,则将max设置为当前字符出现的次数,
                // 并将出现次数最多的字符置为当前字符
                if (map.get(ch[i]) >= max) {
                    max = map.get(ch[i]);
                    ret = ch[i];
                }
            } else {
                map.put(ch[i], 1);
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        // 测试字符
        String str = "a1a2a3bbbcccdddeeefffddda23112211";
        char c = FirstChar.searchFirstChar(str);
        System.out.println(c);
    }
}

Results of the:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44290425/article/details/88560209