배열 arr[n]이 주어지면 여기서 n은 배열의 일부 크기입니다. 작업은 배열이 회문인지 재귀를 사용하지 않는지 확인하는 것입니다. 회문은 MADAM, NAMAN 등과 같이 앞뒤로 읽을 수 있는 시퀀스입니다.
따라서 배열이 회문인지 확인하려면 다음과 같이 배열을 앞뒤로 순회할 수 있습니다. -

재귀에서도 시작과 끝 값이 같아질 때까지 또는 시작과 끝 값이 같지 않을 때 종료하고 주어진 배열이 회문(palindrome)이 아니라는 false를 반환해야 합니다.
예시
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]와 같은지 확인하고 start
- 증가는 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