Given a string, write a recursive function that check if the given string is palindrome, else not palindrome.
Examples :
Input : malayalam
Output : Yes
Reverse of malayalam is also
malayalam.
Input : max
Output : No
Reverse of max is not max.
1) If there is only one character in string
return true.
2) Else compare first and last characters
and recur for remaining substring.
Below is the implementation of above idea :
C++
#include <bits/stdc++.h>
using namespace std;
bool isPalRec(char str[],
int s, int e)
{
if (s == e)
return true;
if (str[s] != str[e])
return false;
if (s < e + 1)
return isPalRec(str, s + 1, e - 1);
return true;
}
bool isPalindrome(char str[])
{
int n = strlen(str);
if (n == 0)
return true;
return isPalRec(str, 0, n - 1);
}
int main()
{
char str[] = "geeg";
if (isPalindrome(str))
cout << "Yes";
else
cout << "No";
return 0;
}
Check whether the given string is Palindrome using Stack
Given a string str, the task is to find whether the given string is a palindrome or not using stack.
Examples:
Input: str = “geeksforgeeks”
Output: No
Input: str = “madam”
Output: Yes
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* stack;
int top = -1;
void push(char ele)
{
stack[++top] = ele;
}
char pop()
{
return stack[top--];
}
int isPalindrome(char str[])
{
int length = strlen(str);
stack = (char*)malloc(length * sizeof(char));
int i, mid = length / 2;
for (i = 0; i < mid; i++) {
push(str[i]);
}
if (length % 2 != 0) {
i++;
}
while (str[i] != '\0') {
char ele = pop();
if (ele != str[i])
return 0;
i++;
}
return 1;
}
int main()
{
char str[] = "madam";
if (isPalindrome(str)) {
printf("Yes");
}
else {
printf("No");
}
return 0;
}
|
Comments
Post a Comment