palindrome main function code example
Example 1: reads the string in then determines if the string is a palindrome.
using namespace std;
// Iterative function to check if given string is a palindrome or not
bool isPalindrome(string str)
{
int low = 0;
int high = str.length() - 1;
while (low < high)
{
// if mismatch happens
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
int main()
{
string str = "XYXYX";
if (isPalindrome(str))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}
Example 2: reads the string in then determines if the string is a palindrome.
using namespace std;
// Recursive function to check if str[low..high] is a palindrome or not
bool isPalindrome(string str, int low, int high)
{
// base case
if (low >= high)
return true;
// return false if mismatch happens
if (str[low] != str[high])
return false;
// move to next the pair
return isPalindrome(str, low + 1, high - 1);
}
int main()
{
string str = "XYBYBYX";
int len = str.length();
if (isPalindrome(str, 0, len - 1))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}