Skip to Content
CoursesCSC102การตรวจสอบ Pangram

การตรวจสอบ Pangram

โจทย์

A pangram is a string that contains every letter of the English alphabet at least once. Your task is to determine whether a given sentence is a pangram. Ignore case sensitivity. Return “pangram” if the sentence is a pangram and “not pangram” otherwise.

Input:

  • A single line containing the input string 𝑠. Each character of the string 𝑠 will be an ASCII character.

Output:

  • Return the string “pangram” if the input string is a pangram; otherwise, return “not pangram”.
InputOutput
The quick brown fox jumps over the lazy dogPangram
This is not a pangram.Not Pangram

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine() .toLowerCase() .replace(" ", ""); String alphabets = "abcdefghijklmnopqrstuvwxyz"; int[] alphabetCount = new int[26]; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); int index = alphabets.indexOf(c); if (index < 0) continue; alphabetCount[index]++; } boolean isPangram = true; for (int count : alphabetCount) { if (count < 1) { isPangram = false; } } System.out.println(isPangram ? "Pangram" : "Not Pangram"); } }

คำอธิบาย

1. การประกาศคลาสและรับข้อมูล

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
  • ใช้ Scanner สำหรับรับข้อมูลข้อความ

2. การเตรียมข้อความ

String text = scanner.nextLine() .toLowerCase() .replace(" ", "");
  • รับข้อความและแปลงเป็น:
  • ตัวพิมพ์เล็กทั้งหมด (.toLowerCase())
  • ลบช่องว่างทั้งหมด (.replace(" ", ""))

3. การเตรียมตัวแปรสำหรับตรวจสอบ

String alphabets = "abcdefghijklmnopqrstuvwxyz"; int[] alphabetCount = new int[26];
  • สร้างสตริงอ้างอิงตัวอักษร a-z
  • สร้างอาเรย์เก็บจำนวนครั้งที่พบแต่ละตัวอักษร

4. การนับจำนวนตัวอักษร

for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); int index = alphabets.indexOf(c); if (index < 0) continue; alphabetCount[index]++; }
  • วนลูปทุกตัวอักษรในข้อความ
  • ดึงตัวอักษรแต่ละตัวด้วย charAt(i)
  • หาตำแหน่งในสตริง alphabets ด้วย indexOf()
  • ถ้าไม่พบ (index < 0) ให้ข้ามไป
  • เพิ่มค่าในอาเรย์นับจำนวนตามตำแหน่งที่พบ

5. การตรวจสอบ Pangram

boolean isPangram = true; for (int count : alphabetCount) { if (count < 1) { isPangram = false; } }
  • ตั้งค่าเริ่มต้นเป็น true
  • ตรวจสอบทุกช่องในอาเรย์นับจำนวน
  • ถ้าพบช่องใดมีค่าน้อยกว่า 1 แสดงว่าไม่มีตัวอักษรนั้น
  • เปลี่ยนเป็น false เพราะไม่ใช่ Pangram

6. การแสดงผล

System.out.println(isPangram ? "Pangram" : "Not Pangram");
  • ใช้ Ternary operator เพื่อแสดงผลตามค่า isPangram

แผนภาพการทำงาน

ตัวอย่างการทำงาน

  1. Input: “The quick brown fox jumps over the lazy dog”
  • เป็น Pangram เพราะมีทุกตัวอักษร
  • Output: “Pangram”
  1. Input: “Hello World”
  • ไม่เป็น Pangram เพราะมีตัวอักษรไม่ครบ
  • Output: “Not Pangram”
ปรับปรุงล่าสุด