กำหนดอาร์เรย์ arr[n] โดยที่ n คือขนาดของอาร์เรย์ ภารกิจคือการค้นหาว่าอาร์เรย์นั้นเป็นพาลินโดรมหรือไม่ได้ใช้การเรียกซ้ำ Palindrome เป็นซีเควนซ์ที่สามารถอ่านย้อนหลังและไปข้างหน้าได้เหมือนกัน เช่น MADAM, NAMAN เป็นต้น
ดังนั้นในการตรวจสอบอาร์เรย์ว่าเป็น palindrome หรือไม่เพื่อให้เราสามารถสำรวจอาร์เรย์จากด้านหลังและไปข้างหน้าได้เช่น -

ในการเรียกซ้ำ เราต้องเปลี่ยนค่าเริ่มต้นและสิ้นสุดจนกว่าจะเท่ากัน หรือเมื่อค่าเริ่มต้นและสิ้นสุดไม่เท่ากัน ให้ออกและคืนค่าเท็จว่าอาร์เรย์ที่ระบุไม่ใช่พาลินโดรม
ตัวอย่าง
Input: arr[] = { 2, 3, 4, 3, 2}
Output: Yes, the array is Palindrome
Explanation: the array is identical from start (2, 3, 4, 3, 2) and end (2, 3, 4, 3, 2).
Input: arr[] = {1, 2, 3, 4}
Output: No, the array is not Palindrome
Explanation: The array is not identical from start (1, 2, 3, 4) and end (4, 3, 2, 1). แนวทางที่ใช้ด้านล่างมีดังนี้ −
เราจะทำซ้ำขั้นตอนต่อไปนี้ -
- ตรวจสอบ arr[start] เท่ากับ arr[end] และเริ่มต้น
- การเพิ่มขึ้นเริ่มต้นด้วย 1 และการลดลงสิ้นสุดด้วย 1
- ไปที่ขั้นตอนที่ 1
อัลกอริทึม
Start
In function int palindrome(int arr[], int start, int end)
Step 1-> If start >= end then,
Return 1
Step 2-> If arr[start] == arr[end] then,
Return palindrome(arr, start + 1, end - 1)
Step 3-> Else {
Return 0
In fucntion int main()
Step 1-> Declare and initialize an array arr[]
Step 2-> Declare and initialize n = sizeof(arr) / sizeof(arr[0]
Step 3-> If palindrome(arr, 0, n - 1) == 1 then,
Print "Yes, the array is Palindrome”
Step 4-> Else
Print "No, the array is not Palindrome”
Stop ตัวอย่าง
#include <stdio.h>
// Recursive pallindrome function that returns 1 if
// palindrome, 0 if it is not
int palindrome(int arr[], int start, int end) {
// base case
if (start >= end) {
return 1;
}
if (arr[start] == arr[end]) {
return palindrome(arr, start + 1, end - 1);
} else {
return 0;
}
// Driver code
int main() {
int arr[] = { 1, 2, 0, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
if (palindrome(arr, 0, n - 1) == 1)
printf("Yes, the array is Palindrome\n");
else
printf("No, the array is not Palindrome\n");
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
Yes, the array is Palindrome