Wednesday, 15 October 2014

String is Palindrome or not using Recursion

We know iterative ways to find out whether string is palindrome or not but here i will be discussing the recursive way.

Algorithm
  1. Transform the string to lower case to cater cases like Nitin.
  2. Then traverse the string from start and end using recursion till start is less than end.   
Input      : a string 
Output   : String is (not) Palindrome

Implementation

#include<iostream>
#include<string>
using namespace std;
bool Palindrome(string s, int start,int end)
{
     if(start>end)
           return true;
     else if(s[start]==s[end])
     {
           return Palindrome(s,++start,--end);
     }
     else
           return false;
        
     
}
int main()
{
    string s;
    cin>>s;
  //Converting the string to lower case
    transform(s.begin(),s.end(),s.begin(),::tolower);
    if(Palindrome(s,0,s.length()-1))
       cout<<"String is Palindrome";
    else
       cout<<"String is not Palindrome";
      
    getchar();
    return 0;    
   
}
 

Please comment if you find anything incorrect
                                                                               

No comments:

Post a Comment