Advertisement
DeepRest

Palindromic Substrings

May 22nd, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. #Manacher O(n) space and time
  2.  
  3. class Solution:
  4.     def countSubstrings(self, s: str) -> int:
  5.         p = self.preprocessString(s)
  6.         n = len(p)
  7.  
  8.         l, r, c = -1, -1, -1
  9.         pals = [1]*n
  10.        
  11.         for i in range(n):  
  12.             if i > r:
  13.                 l = c = r = bound = i
  14.             else:
  15.                 mirr = 2*c - i  
  16.                 pals[i] = min(pals[mirr], 2*(r - i) + 1)
  17.                 bound = mirr - pals[mirr]//2
  18.    
  19.             if bound != l:  
  20.                 continue
  21.            
  22.             l = i - pals[i]//2
  23.             c = i
  24.             while l > 0 and r < n-1 and p[l-1] == p[r+1]:
  25.                 pals[i] += 2
  26.                 l -= 1
  27.                 r += 1  
  28.        
  29.         res = 0
  30.         for x in pals:
  31.             res += (x+1)//4
  32.        
  33.         return res
  34.    
  35.     def preprocessString(self, s):  
  36.         n = len(s)
  37.         res = ["#"]*(2*n+1)
  38.        
  39.         for i in range(n):
  40.             res[2*i+1] = s[i]
  41.        
  42.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement