C++ Program to check if a given String is Palindrome or not
Last Updated :
12 Sep, 2023
Given a string S consisting of N characters of the English alphabet, the task is to check if the given string is a palindrome. If the given string is a palindrome, then print “Yes“. Otherwise, print “No“.
Note: A string is said to be palindrome if the reverse of the string is the same as the string.
For example, The string “racecar” is a palindrome because the reverse of the string is the same as the original string.
Method 1: Using the Inbuilt reverse() Function in the STL
The simplest approach is to use the inbuilt reverse() function in the STL.
Algorithm
- Copy the string S to another string, say P, and then reverse the string S.
- Now check if the string S is equal to the string P and then print “Yes“. Otherwise, print “No“.
C++ Program to Check if a Given String is Palindrome or Not
C++
#include <bits/stdc++.h>
using namespace std;
string isPalindrome(string S)
{
string P = S;
reverse(P.begin(), P.end());
if (S == P) {
return "Yes" ;
}
else {
return "No" ;
}
}
int main()
{
string S = "ABCDCBA" ;
cout << isPalindrome(S);
return 0;
}
|
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Method 2: By Traversing the String
The above approach can be optimized in space complexity by traversing the string and checking whether the character at the ith index is equal to the character at the (N-i-1)th index for every index in the range [0, N/2].
Algorithm
- Iterate over the range [0, N/2], using the variable i, and in each iteration check if the character at index i and N-i-1 are not equal, then print “No” and break.
- If none of the above cases satisfy, then print “Yes“.
C++ Program to Check if a Given String is Palindrome or Not
C++
#include <bits/stdc++.h>
using namespace std;
string isPalindrome(string S)
{
for ( int i = 0; i < S.length() / 2; i++) {
if (S[i] != S[S.length() - i - 1]) {
return "No" ;
}
}
return "Yes" ;
}
int main()
{
string S = "ABCDCBA" ;
cout << isPalindrome(S);
return 0;
}
|
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Related Articles
Share your thoughts in the comments
Please Login to comment...