面試題:尋找一個字符串中出現次數最多的字符以及出現的次數

要求編寫代碼實現:尋找一個字符串中出現次數最多的字符以及出現的次數。java

解法一:用刪除法實現 (挺巧妙的一種)

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);
    }
}
相關文章
相關標籤/搜索