I want to find Palindrome of a word. Whats Wrong Here?
main function:
int size;
string input;
cin>>input;
size = input.length();
if(testPalindrome(input,size-1,0))
cout<<"It's Palindrome";
else
cout<<"It's not Palindrome";
And the testPalindrome function is:
bool testPalindrome (string pal , int last, int first){
if (pal[first] != pal[last])
return false;
else{
if (first<last)
testPalindrome(pal,last-1,first+1);
else
return true;
}
}
I have read this link and found the answer for determining Palindromes, but why this one is not working?
I think you forgot the return statement in the function
if (first<last)
return testPalindrome(pal,last-1,first+1);
^^^^^^^
Usually the first parameter of a range specifies the lower value and the second parameter specifies either the upper value of the range that is not included in the range or the number of elements in the sequence..
And the first parameter should be declared as having constant reference type because the string itself is not changed and you will escape additional memory allocation.
The recursive function can be written like
#include <iostream>
#include <string>
bool testPalindrome(const std::string &s,
std::string::size_type i,
std::string::size_type n)
{
return n < 2 || (s[i] == s[n-1] && testPalindrome(s, i + 1, n - 2) );
}
int main()
{
std::cout << testPalindrome("abba", 0, 4) << std::endl;
std::cout << testPalindrome("aba", 0, 3) << std::endl;
std::cout << testPalindrome("aa", 0, 2) << std::endl;
std::cout << testPalindrome("a", 0, 1) << std::endl;
std::cout << testPalindrome("ab", 0, 2) << std::endl;
return 0;
}
The program output is
1
1
1
1
0
The simplest way to check whether an object of the type std::string
is a palindrome is to write the expression
s == std::string( s.rbegin(), s.rend() )