# Palindrome word & sentence

  • Palindrome is a word, sentence, or sequence that reads the same backwards and forwards.

  • Palindrome Word : e.g. racecar

  • Palindrome Sentence : e.g. No word, no bond, row on.

  • To check if two strings are palindrome or not we will compare characters from left and right side excluding the spaces and special characters (because we are only considering alphabets and numbers) and if at any point the characters are not same it means that it is not palindrome. Otherwise if we reach the middle of the word and all characters match it means it is palindrome.

# Source Code - C++

#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;

//Function to Check Palindrome
bool Palindrome(string s)
{
  int i,j;
  i=0;
  j=s.length()-1;

  while(i<j)
  {
       //removing spaces and special characters
    while(i<j && isalnum(s[i])==0)
      i++;
    while(i<j && isalnum(s[j])==0)
      j--;

   //Checking if not palindrome
   if(toupper(s[i])!=toupper(s[j]))
    {
     return false;
    }
   else
   {
    i++;
    j--;
   }

  }
  return true;
}

//Main Function
int main() {

  string s;
  getline(cin,s);
  
  int ans=Palindrome(s);

  if(ans==1)
   cout<<"YES\n";
  else
   cout<<"NO\n";

 return 0;
}

Learn More


  • Palindrome word & sentence