面试题:寻找一个字符串中出现次数最多的字符以及出现的次数

2,680 阅读3分钟

要求编写代码实现:寻找一个字符串中出现次数最多的字符以及出现的次数。

解法一:用删除法实现 (挺巧妙的一种)

public class FindTheMostAppearChar {
  public static void main(String[] args) {
    deleteMethodToAchieve();
  }
  
    /**
     * 用删除法实现 (挺巧妙的)
     * 解题思路:每次取出字符串的第一个字符,将字符串中与第一个字符相同的字符全部删掉,
     * 然后通过计算删除前后字符串的长度来确定该字符在字符串出现的次数,最终比较出出现次数最多的字符
     */
    public static void deleteMethodToAchieve() {
        Scanner scanner = new Scanner(System.in);
        String string = scanner.nextLine().trim();
        scanner.close();
        int max_length = 0;
        String max_str = "";
        while (string.length() > 0) {
            String firstChar = string.substring(0,1);
            int length = string.length();
            string = string.replaceAll(firstChar, "");
            if (length - string.length() > max_length) {
                max_length = length - string.length();
                max_str = firstChar;
            }
        }
        System.out.println("出现次数最多的字符是:" + max_str + ",出现的次数:" + max_length);
    }
}

解法二:用查找法实现

public class FindTheMostAppearChar {
  public static void main(String[] args) {
    hashMapMethodToAchieve();
  }
  
    /**
     * 用字符数组查找法实现
     * 解题思路:先将字符串拆分成字符数组,然后转存到 HashMap 集合中,
     * 该集合的key为字符串中出现的字符,value为对应字符串出现的次数。
     * 最后只需要在HashMap集合中找到Value值最大的key即可。
     */
    public static void hashMapMethodToAchieve() {
        Scanner scanner = new Scanner(System.in);
        String string = scanner.nextLine().trim();
        scanner.close();
        // 将字符串转换成字符数组
        char[] arr = string.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        // key为出现的字符,value 为该字符出现的次数,将字符数组转存在 HashMap 中
        if (arr != null && arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                if (map.get(arr[i]) != null) {
                    // 若不为空,说明已经存在相同的字符,则 value 值在原来的基础上加1
                    map.put(arr[i],map.get(arr[i]) + 1);
                } else {
                    map.put(arr[i], 1);
                }
            }
        }
      
      	// 查找出出现次数最多的字符以及出现的次数也有多种写法
      	FindTheMostCharByMap(map); // 查找写法一:用 Iterator 遍历 Map 来查找
      	
        // FindTheMostCharByMapEntry(map); // 查找写法二:用 Map.Entry 提高效率
      
        // FindTheMostCharByForLoop(map, arr); // 查找写法三:直接用 for 循环来遍历查找
    }
  
  // 查找写法一:用 Iterator 遍历 Map 来查找
  public statice void FindTheMostCharByMap(Map<Character, Integer> map) {
        Set<Character> keys = map.keySet(); // 获取所有的key
        Iterator iterator = keys.iterator(); // 实例化 Iterator
        Character maxKey = (Character) iterator.next(); //定义第一个为最大的value和对应的key
        int maxValue = map.get(maxKey);
        while (iterator.hasNext()) {
            Character temp = (Character) iterator.next();
            if (maxValue < map.get(temp)) {
                maxKey = temp;
                maxValue = map.get(temp);
            }
        }
        System.out.println("出现次数最多的字符是:" + maxKey + ", 出现的次数:" + maxValue);
  }
  
  // 查找写法二:用 Map.Entry 提高效率
  public static void FindTheMostCharByMapEntry(Map<Character, Integer> map) {
        Iterator iterator = map.entrySet().iterator();
        Map.Entry entry = (Map.Entry) iterator.next();
        char maxKey = (char) entry.getKey(); // 获取key
        int maxValue = (int) entry.getValue(); // 获取value
        while (iterator.hasNext()) {
            entry = (Map.Entry) iterator.next();
            char tempKey = (char) entry.getKey();
            int tempValue = (int) entry.getValue();
            if (maxValue < tempValue) {
                maxKey = tempKey;
                maxValue = tempValue;
            }
        }
    	System.out.println("出现次数最多的字符是:" + maxKey + ", 出现的次数:" + maxValue);
  }
    
  // 查找写法三:直接用 for 循环来遍历查找
  public static void FindTheMostCharByForLoop(Map<Character, Integer> map, char[] arr) {
        int maxValue = map.get(arr[0]);
        char maxKey = ' ';
        for (int i = 0; i < arr.length; i++) {
            if (maxValue < map.get(arr[i])) {
                maxValue = map.get(arr[i]);
                maxKey = arr[i];
            }
        }
    	System.out.println("出现次数最多的字符是:" + maxKey + ", 出现的次数:" + maxValue);
  }
  
}

解法三:用排序法实现

public class FindTheMostAppearChar {
  public static void main(String[] args) {
    sortMethodToAchieve();
  }
  
     /**
     * 用排序法实现
     * 解题思路:先将字符串转换成字符数组,然后对字符数组进行排序,
     * 统计每个字符重复出现的次数,最后比较得出出现次数最多的字符以及出现次数
     */
    public static void sortMethodToAchieve() {
        Scanner scanner = new Scanner(System.in);
        String string = scanner.nextLine().trim();
        scanner.close();
        char[] arr = string.toCharArray();
        Arrays.sort(arr); // 对数组进行排序
        char maxValue = 'a'; // 记录出现次数最多的元素
        int maxCount = 0; // 记录出现次数
        int count = 1;
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] == arr[i+1]) {
                count++;
            }
            if (arr[i] != arr[i+1]) {
                if (count > maxCount) {
                    maxCount = count;
                    maxValue = arr[i];
                }
                count = 1;
            }
        }
        System.out.println("出现次数最多的字符是:" + maxValue + ", 出现的次数:" + maxCount);
    }
}