Palindromic Substrings

Given a string, your task is to count how many palindromic substrings in this string. Tags: String

Try It!

Discussion

Video

Solution

class Solution:
    def countSubstrings(self, s: str) -> int:
        count = 0
        for i in range(len(s)):
            # odd
            j = i
            k = i
            while j >= 0 and k < len(s) and s[j] == s[k]:
                count += 1
                j -= 1 
                k += 1

            # even
            j = i
            k = i + 1
            while j >= 0 and k < len(s) and s[j] == s[k]:
                count += 1
                j -= 1
                k += 1
                
        return count