การตรวจสอบข้อความพาลินโดรม
โจทย์
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.”
| Input | Output |
|---|---|
| dad | dad is a palindrome. |
| moon | moon 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
- เริ่มต้น: left = 0 (
d), right = 2 (d) - ตรวจสอบ:
dเท่ากับd✅ - เลื่อนเข้ามา: left = 1 (
a), right = 1 (a) - จบการทำงาน: เป็น palindrome ✅
กรณีที่ 2: ข้อความ moon
- เริ่มต้น: left = 0 (
m), right = 3 (n) - ตรวจสอบ:
mไม่เท่ากับn❌ - จบการทำงาน: ไม่เป็น palindrome ❌
ปรับปรุงล่าสุด