Check Palindrome String

Check Palindrome String” is a very popular and basic problem of string data structure. Here, we are given a string of length ‘n’ and our task is to check whether given string is palindromic string or not.

A palindromic string is a string which is same whether scanning from left to right or right to left.

Example:

INPUT:
MAD#$#DAM
OUTPUT:
MAD#$#DAM is a palindromic string.
 
INPUT:
Helpmestudybro
OUTPUT:
Helpmestudybro is not a palindromic string.

There are basically two methods to do the same task:

  1. With using auxiliary string.
  2. Without using auxiliary string.

METHOD 1: With using auxiliary string

Copy the given string to auxiliary string. Reverse the auxiliary string. Finally, if auxiliary string and original string is same, then original string is palindromic string. Otherwise, not.


C++ Program to check whether given string is palindromic string or not is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    string str;  
    cout<<"Enter the string:\n";  
    cin>>str;  
    string temp = str;  
    reverse(temp.begin(),temp.end());  
    if(str == temp)  
    cout<<str<<" is palindromic string";  
    else  
    cout<<str<<" is not a palindromic string";  
}  
OUTPUT:
Enter the string: madam 
madam is palindromic string
Time Complexity:
O(n), where ‘n’ is the length of string

METHOD 2: Without Auxiliary string

Set two iterators, ‘i’ and ‘j’, pointing at first character of string and last character of string respectively. Initialize a flag variable with 0. Now, scan the string and compare characters at index ‘i’ and ‘j’.

If character at index ‘i’ and ‘j’ are same , then increment ‘i’ and decrement ‘j’ and continue scanning, Else, set flag with 1 and break the loop.

If flag is 0, string is palindromic string, else string is not palindromic string.

C++ Program to check whether given string is palindrome or not is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    string str;  
    cout<<"Enter the string:\n";  
    cin>>str;  
    int flag = 0;  
    for(int i = 0, j = str.length()-1; j>=i; i++,j--)  
    {  
        if(str[i]!=str[j])  
        {  
            flag = 1;  
            break;  
        }  
    }  
    if(flag == 0)  
    cout<<str<<" is palindromic string";  
    else  
    cout<<str<<" is not a palindromic string";  
}  

OUTPUT:
Enter the string: madam 
madam is palindromic string
Time Complexity:
O(n), where ‘n’ is the length of string

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *