-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathpalindrome.cpp
69 lines (47 loc) · 1.09 KB
/
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
#include<iostream>
#include<string>
#include<cstring> //to use the strlen(char) function
//implementing it using a C type string
using namespace std;
int palindrome(char *a)
{
int i=0;
int j = strlen(a)-1;
while(i<=j && a[i]==a[j]) {
//true condition , simply change i and j indices
i++;
j--;
}
if(i<j) {
cout<<"Not palindrome"<<endl;
return 0;
}
else {
cout<<"Palindrome"<<endl;
return 1;
}
}
//recursive program to find whether a string is palindrome or not-in POSTRORDER traversal
bool PalindromeRec(string exp,int i,int j )
{
//base condition-recursion terminates
if(i>j || exp[i]!=exp[j])
return false;
if(exp[i]==exp[j])
return true;
//otherwise simply keep checking for same digits by incrementing i and decrementing j
if(i<=j)
{
return PalindromeRec(exp,i++,j--);
}
}//Time complexity = O(n), spcae complexity = O(n), for recursive call stack
int main() {
// palindrome("nitin");
// palindrome("anish");
cout<<endl;
string str = "raar";
int i = 0;
int j = str.size()-1;
cout<<PalindromeRec(str,i,j);
return 0;
}