647_Palindromic Substrings

647. Palindromic Substrings

Level: medium

Tag: string, dynamic programming

Question

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

The substrings with different start indexes or end indexes are counted as different substrings 
even they consist of same characters.

Note: A palindrome is a word, which reads the same backward as forward.

Example1

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example2

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Idea: (expand around center, dynamic programming, similar to Longest Palindromic Substring Q5)

Loop from the beginning to the end. Take each letter be the center of the substring, and find the number of palindromic substring centered by that letter.

There are two types of center:

  • the letter is the center, such that the palindromic substring has odd number of letters

  • the space on the right of the letter is the center, such that the palindromic substring has even number of letters

Complexity

  • Time:O(n2)O(n^2)

  • Space:O(1)O(1)

Solution

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0

        # dynamic programming
        for i in range(len(s)):
            count += self.helper(s,i,i+1) + self.helper(s,i,i)
        return count




        # helper function to get the number of palindromic substring expanding from s[l:r+1]
        # from center to outer letters
    def helper(self, s, l, r):
        """
        :type s: str
        :type l: num
        :type r: num
        :rtype: str
        """
        count = 0
        while l >= 0 and r <= len(s)-1 and s[l] == s[r]:
            count += 1
            l -= 1
            r += 1
        return count

Last updated