Program to find length of longest palindromic substring after single rotation in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s, which we can rotate at any point exactly once. We have to find the length of the longest palindromic substring we can get by doing this operation.

So, if the input is like s = "elklev", then the output will be 7, as we can rotate between "el" and "klev" to get "levelk". So here the longest palinfromic substring length is 5.

To solve this, we will follow these steps −

  • s2 := concatenate s twice

  • max_len := 0

  • for x in range 0 to size of s − 1, do

    • for y in range 0 to size of s, do

      • temp := s2[from index x to x + y]

      • if temp is palindrome and size of temp > max_len, then

        • max_len := size of temp

  • return max_len

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      s2 = 2 * s
      max_len = 0
      for x in range(len(s)):
         for y in range(len(s) + 1):
            temp = s2[x : x + y]
            if temp == temp[::−1] and len(temp) > max_len:
               max_len = len(temp)
      return max_len
ob = Solution()
s = "elklev"
print(ob.solve(s))

Input

"elklev"

Output

5
raja
Published on 15-Dec-2020 12:33:57
Advertisements