Skip to Content
CoursesCSC102การตรวจสอบข้อความพาลินโดรม

การตรวจสอบข้อความพาลินโดรม

โจทย์

A palindrome is a number, letter combination, word or text that reads the same in both directions. To summarize, a palindrome can be called any set of characters that is symmetrical about its middle.

If the input text is a palindrome, display “The text is a palindrome.” Otherwise, display “The text is not a palindrome.”

InputOutput
daddad is a palindrome.
moonmoon is not a palindrome.

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); int left = 0, right = text.length() - 1; boolean isValid = true; while (left < right) { if (text.charAt(left) != text.charAt(right)) { isValid = false; break; } left++; right--; } if (isValid) { System.out.printf("%s is a palindrome.", text); } else { System.out.printf("%s is not a palindrome.", text); } } }

คำอธิบาย

1. การรับข้อมูล

Scanner scanner = new Scanner(System.in); String text = scanner.nextLine();
  • สร้างตัวแปร scanner เพื่อรับข้อความจากผู้ใช้
  • เก็บข้อความที่รับมาไว้ในตัวแปร text

2. การกำหนดตัวชี้ตำแหน่ง

int left = 0, right = text.length() - 1;
  • left คือตัวชี้ตำแหน่งจากซ้ายสุด (เริ่มที่ 0)
  • right คือตัวชี้ตำแหน่งจากขวาสุด (ความยาวข้อความ - 1)

3. การตรวจสอบ Palindrome

boolean isValid = true; while (left < right) { if (text.charAt(left) != text.charAt(right)) { isValid = false; break; } left++; right--; }
  • ใช้ตัวแปร isValid เพื่อเก็บผลการตรวจสอบ
  • วนลูปตราบใดที่ left น้อยกว่า right
  • เปรียบเทียบตัวอักษรที่ตำแหน่ง left และ right
  • ถ้าไม่เท่ากัน แสดงว่าไม่ใช่ palindrome
  • เลื่อนตำแหน่ง left และ right เข้าหากัน

4. การแสดงผลลัพธ์

if (isValid) { System.out.printf("%s is a palindrome.", text); } else { System.out.printf("%s is not a palindrome.", text); }
  • แสดงผลว่าข้อความเป็น palindrome หรือไม่

หลักการทำงาน

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

กรณีที่ 1: ข้อความ dad

  1. เริ่มต้น: left = 0 (d), right = 2 (d)
  2. ตรวจสอบ: d เท่ากับ d
  3. เลื่อนเข้ามา: left = 1 (a), right = 1 (a)
  4. จบการทำงาน: เป็น palindrome ✅

กรณีที่ 2: ข้อความ moon

  1. เริ่มต้น: left = 0 (m), right = 3 (n)
  2. ตรวจสอบ: m ไม่เท่ากับ n
  3. จบการทำงาน: ไม่เป็น palindrome ❌
ปรับปรุงล่าสุด