Check if a string contains a palindromic sub-string of even length in C++

C++Server Side ProgrammingProgramming

Suppose, we are given a string that contains only lowercase letters. Our task is to find if there exists a substring in the given string that is a palindrome and is of even length. If found, we return 1 otherwise 0.

So, if the input is like "afternoon", then the output will be true.

To solve this, we will follow these steps −

  • for initialize x := 0, when x < length of string - 1, increase x by 1, do −
    • if string[x] is same as string[x + 1], then:
      • return true
  • return false

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool solve(string string) {
   for (int x = 0; x < string.length() - 1; x++) {
      if (string[x] == string[x + 1])
         return true;
   }
   return false;
}
int main() {
   cout<<solve("afternoon") <<endl;
}

Input

"afternoon"

Output

1
raja
Published on 18-Jan-2021 16:16:50
Advertisements