A string is called a palindrome if it reads the same from left to right and right to left.
- A palindrome can be checked by comparing the string with its reversed copy.
- The two-pointer approach checks matching characters from both ends without creating a reversed string.
Examples:
Input: ABCDCBA
Output: ABCDCBA is a palindrome.Input: ABCD
Output: ABCD is not a palindrome.
Approaches to Check if a String is a Palindrome
The following two approaches can be used:
1. Comparing with the Reversed String
In this approach, we create a copy of the string, reverse it using std::reverse(), and compare it with the original string.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(const string& str)
{
string rev = str;
reverse(rev.begin(), rev.end());
return str == rev;
}
int main()
{
string str = "ABCDCBA";
if (isPalindrome(str))
cout << str << " is a palindrome.\n";
else
cout << str << " is not a palindrome.\n";
return 0;
}
Output
ABCDCBA is a palindrome.
Explanation: For "ABCDCBA", reversing the string gives:
Original: ABCDCBA
Reversed: ABCDCBA
Since both strings are identical, the given string is a palindrome.
2. Using the Two-Pointer Approach
This approach compares characters from the beginning and end of the string. Two pointers, left and right, move toward the center.
Approach
- Initialize left at the first character and right at the last character.
- Compare the characters at both positions.
- If they differ, the string is not a palindrome.
- If they match, move left forward and right backward.
- Continue until the pointers meet or cross.
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(const string& str)
{
int left = 0;
int right = str.length() - 1;
while (left < right)
{
if (str[left] != str[right])
return false;
left++;
right--;
}
return true;
}
int main()
{
string str = "ABCDCBA";
if (isPalindrome(str))
cout << str << " is a palindrome.\n";
else
cout << str << " is not a palindrome.\n";
return 0;
}
Output
ABCDCBA is a palindrome.
Explanation: The comparisons for "ABCDCBA" are:
A == A
B == B
C == C
D
The pointers reach the middle without finding any mismatch, so the string is a palindrome.
For "ABCD":
A != D
Since the first and last characters are different, the string is not a palindrome.