In this tutorial, we learn how to check whether a given string is palindrome or not using recursion in C++ language. Time complexity: O(n), Auxiliary space: O(n).
Input: racecar
Output: true
The reverse of a racecar is a racecar.
Input: coder
Output: false
Reverse of coder is redoc.
1) If there is only one character in the string return true.
2) Else compare the first and last characters and recur for the remaining substring.
#include<bits/stdc++.h> using namespace std; // A recursive function that // check a string is // palindrome or not. bool helper(char input[],int size) { //if string is empty if(size<=0) { return true; } //checks first and last character of string else if (input[0]!=input[size]) { return false; } return helper(input+1,size-2); } bool checkPalindrome(char input[]) { int size=strlen(input); if(size==1) return true; return helper(input,size-1); } // Driver Code int main() { char str[] = "racecar"; if (checkPalindrome(str)) cout << "true"; else cout << "false"; return 0; }
Submitted by ARYA CHANDRAKAR (Arya)
Download packets of source code on Coders Packet
Comments