經典入門題:給定字符串 "today is a special day",找出出現次數最多的字符及其次數。本文提供標準 HashMap 計頻解法、完整可運行代碼、邊界情況處理及進階優化思路。
char[] 數組。HashMap 統計每字符出現次數。value 最大的鍵值對。
import java.util.*;
public class MaxCharFrequency {
public static void main(String[] args) {
String str = "today is a special day";
Map freq = new HashMap<>();
// 1. 統計頻次
for (char c : str.toCharArray()) {
freq.merge(c, 1, Integer::sum); // Java 8 寫法,等價 put/get/put
}
// 2. 找最大值 (處理並列情況:此處取首個遇到的)
Map.Entry maxEntry = null;
for (Map.Entry e : freq.entrySet()) {
if (maxEntry == null || e.getValue() > maxEntry.getValue()) {
maxEntry = e;
}
}
// 3. 輸出
if (maxEntry != null) {
System.out.printf("字符: '%c' 出現次數最多, 共 %d 次%n", maxEntry.getKey(), maxEntry.getValue());
} else {
System.out.println("字符串為空");
}
}
}
字符: 'a' 出現次數最多, 共 4 次
驗證:today is a special day 中 a 出現 4 次 (t**a**y, **a**, speci**a**l, d**a**y),確為最高。
| 情況 | 處理 |
|---|---|
| 空字符串 | 返回提示或拋異常 |
| 多字符並列最高 | 可返回 List |
| 區分大小寫 | 默認區分;不區分時統一 toLowerCase() |
| 超長字符串/流式處理 | 用 IntStream 或外部排序+歸併 |
| 性能極致 | 字符範圍固定時用 int[65536] 數組替代 HashMap |
str.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.ifPresent(e -> System.out.println(e.getKey() + ":" + e.getValue()));
String.toCharArray():字符串轉字符數組Map.merge(key, value, remapFn):原子性更新,簡化 if/elseMap.Entry.comparingByValue():按值比較的 Comparator此題考察基礎集合操作與流程控制,掌握 HashMap 計頻模板,可解決詞頻統計、找眾數、檢測異位詞等大類問題。