เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

สร้างแอปพลิเคชันวิเคราะห์ข้อความ

คุณกำลังพัฒนาแอปพลิเคชันวิเคราะห์ข้อความที่ต้องนับความถี่ของคำในเอกสาร โดยต้องออกแบบโซลูชันที่มี time complexity เหมาะสมที่สุดสำหรับการค้นหาคำ

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การปรับแต่งโค้ดใน Java

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ดึงค่า currentCount ของคำที่มีอยู่ใน frequency map แล้ว
  • เพิ่มค่าจำนวนนับและอัปเดตค่าใหม่ลงใน frequency map
  • หากคำนั้นยังไม่มีใน frequency map ให้เพิ่มเข้าไป

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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;
    }
}
แก้ไขและรันโค้ด