Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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.

Example 1:

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

Example 2:

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

My code:

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        self.record_dict={}
        count=self.check_string(s)
        #print(self.record_dict)
        return count
    def check_string(self,s):
        if len(s)<=1:
            return len(s)
        
        if s in self.record_dict:
            return self.record_dict[s]
        count=0
        for k in range(len(s)):
            tmp_str=s[k:]
            if tmp_str==tmp_str[::-1]:
                count+=1
        result2=self.check_string(s[:len(s)-1])
        count+=result2
        self.record_dict[s]=count
        return self.record_dict[s]
            
        

Solution: https://leetcode.com/problems/palindromic-substrings/