开始使用免费开始使用

实现文本分析应用

您正在开发一个文本分析应用,需要统计文档中每个单词的出现频率。请实现一种在单词查找方面具备最优时间复杂度的方案。

本练习是课程的一部分

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;
    }
}
编辑并运行代码