-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path05_is_palindrome.cpp
118 lines (95 loc) · 2.85 KB
/
05_is_palindrome.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
Problem Name: Is Palindrome?
Take as input N, a number.
Take N more inputs and store that in an array.
Write a RECURSIVE function which tests if the array is a palindrome and returns a Boolean value. Print the value returned.
Input Format: Enter a number N , add N more numbers
Constraints: NONE
Output Format: Display the Boolean result
Sample Input: 4
1
2
2
1
Sample Output: true
Explanation: NA
*/
#include <iostream>
using namespace std;
bool isPalindrome(int arr[], int range){
int start = 0;
int end = range-1;
while(start < end){
if(arr[start] != arr[end]){
return false;
}
start++;
end--;
}
return true;
}
bool isPalindromeRecursive(int arr[], int end, int start=0 ){ // default value of start=0 if value not assigned
// if string is empty return false
if (end == 0){
return false;
}
// if length of string is one, then it is palindrome
if(end == 1){
return true;
}
// if start is greater than end return true
if(start > end-1){
return true;
}
// check first and last character
if(arr[start] != arr[end-1]){
return false;
}else{
return isPalindromeRecursive(arr, --end, ++start); // recursive call
}
}
int main(){
int range;
cout << "Enter total numbers: ";
cin >> range;
int arr[range];
for(int idx=0; idx<=range-1; idx++){
cin >> arr[idx];
}
// bool status = isPalindrome(arr, range); // two pointer approach
bool status = isPalindromeRecursive(arr, range); // recursive call
if(status){
cout << "true";
}else{
cout << "false";
}
cout << endl;
return 0;
}
/*
Approach:
Loop over the array and compare the element from left end of the array with
the corresponding element from the right end of the array.
At any point, if the elements do not match, terminate the loop.
If the whole loop completed, then the array is palindrome.
Code:
public boolean isPalindrome(int[] array) {
int length = array.length;
for (int index = 0; index < array.length; index++) {
// get the element from the start
int start = array[index];
// get corresponding element from end
int end = array[--length];
// check if elements till the middle have been compared
if (length < index) {
return true;
}
// if start element is not the same as end element, the array is not palindrome
if (start != end) {
return false;
}
}
// if the control reaches here, means all the elements were same
return true;
}
*/