開始使用免費開始

實作文字分析應用程式

你正在開發一個文字分析應用程式,需要計算文件中各單字的出現頻率。你必須實作一個在單字查找上具最佳時間複雜度的解決方案。

本練習屬於課程

Java 程式碼最佳化

檢視課程

練習說明

  • 當單字已存在於頻率對應表時,先取得該單字的 currentCount
  • 將其加 1,並以更新後的值回寫到頻率對應表。
  • 如果該單字先前不在頻率對應表中,將它加入。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class Main {
    public static void main(String[] args) {
        TextAnalyzer analyzer = new TextAnalyzer();
        
        List words = Arrays.asList(
            "Java", "is", "a", "programming", "language", 
            "Java", "is", "widely", "used", "for", "building", "applications",
            "Many", "programmers", "use", "Java", "for", "web", "development", "and", "Android", "apps"
        );
        
        Map wordFrequency = analyzer.buildWordFrequencyMap(words);
        
        System.out.println("Word frequency analysis:");
        for (Map.Entry entry : wordFrequency.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue() + " occurrences");
        }
    }
}

class TextAnalyzer {
    public Map buildWordFrequencyMap(List words) {
        Map frequencyMap = new HashMap();
        
        for (String word : words) {
            if (word.isEmpty()) {
                continue;
            }
            
            word = word.toLowerCase();
            
            if (frequencyMap.containsKey(word)) {
                // Retrieve the frequency of the word
                int currentCount = ____.get(____);
                // Increment the frequency of the word
                frequencyMap.put(____, currentCount + 1);
            } else {
                // If the frequency map does not have the word, add it.
                ____.____(word, 1);
            }
        }
        
        return frequencyMap;
    }
}
編輯並執行程式碼