做题笔记:单词出现频率统计 | 豆包MarsCode AI刷题

129 阅读2分钟

做题笔记:单词出现频率统计

问题理解

题目要求统计一个英文句子中每个单词的出现次数,并将结果按字母顺序排序后输出。输出格式为 单词:次数,例如 "hello:2"

数据结构选择

  1. Map:用于存储单词及其出现次数。Java 中可以使用 HashMap 或 TreeMap
  2. List:用于存储排序后的单词。Java 中可以使用 ArrayList

算法步骤

1. 拆分句子

String[] words = s.split("\\s+");
  • 正则表达式 \s+:用于匹配一个或多个空白字符(空格、制表符等)。
  • split 方法:将字符串按照正则表达式拆分为单词数组。

2. 统计单词出现次数

Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
  • HashMap:用于存储单词及其出现次数。
  • getOrDefault 方法:如果单词不存在于 HashMap 中,则返回默认值 0,然后加 1

3. 排序

List<String> sortedWords = new ArrayList<>(wordCount.keySet());
Collections.sort(sortedWords);
  • ArrayList:用于存储排序后的单词。
  • Collections.sort:对单词列表按字母顺序排序。

4. 格式化输出

List<String> result = new ArrayList<>();
for (String word : sortedWords) {
 result.add(word + ":" + wordCount.get(word));
}
-   **格式化字符串**:将单词和次数格式化为 `单词:次数` 的形式。
  • 添加到结果列表:将格式化后的字符串添加到结果列表中。

代码详解

import java.util.*;

public class Main {
public static List<String> solution(String s) {
    // 1. 拆分句子
    String[] words = s.split("\\s+");
    
    // 2. 统计单词出现次数
    Map<String, Integer> wordCount = new HashMap<>();
    for (String word : words) {
        wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
    }
    
    // 3. 排序
    List<String> sortedWords = new ArrayList<>(wordCount.keySet());
    Collections.sort(sortedWords);
    
    // 4. 格式化输出
    List<String> result = new ArrayList<>();
    for (String word : sortedWords) {
        result.add(word + ":" + wordCount.get(word));
    }
    
    return result;
}

public static void main(String[] args) {
    System.out.println(solution("New to Python or choosing between Python 2 and Python 3 Read Python 2 or Python 3").equals(List.of("2:2", "3:2", "New:1", "Python:5", "Read:1", "and:1", "between:1", "choosing:1", "or:2", "to:1")));
    System.out.println(solution("hello world hello python").equals(List.of("hello:2", "python:1", "world:1")));
    System.out.println(solution("the quick brown fox jumps over the lazy dog").equals(List.of("brown:1", "dog:1", "fox:1", "jumps:1", "lazy:1", "over:1", "quick:1", "the:2")));
}
}
### 总结知识点
  1. 字符串操作:使用 split 方法拆分字符串。
  2. Map 的使用HashMap 用于统计单词出现次数,TreeMap 可以自动按字母顺序排序。
  3. List 的使用ArrayList 用于存储排序后的单词。
  4. 排序:使用 Collections.sort 对列表进行排序。
  5. 格式化输出:将单词和次数格式化为指定格式。

学习建议

  1. 基础知识:掌握 Java 基础知识,如字符串操作、集合框架(Map、List)、排序算法等。
  2. 实践练习:多做类似的字符串处理题目,熟悉各种字符串操作和集合框架的使用。
  3. 调试技巧:学会使用调试工具,逐步分析代码执行过程,找出问题所在。
  4. 代码优化:在掌握基本实现后,尝试优化代码,如使用更高效的排序方法或数据结构。

通过不断练习和总结,可以逐步提高编程能力,掌握更多高级技巧。