Skip to content

Latest commit

 

History

History
54 lines (34 loc) · 1.04 KB

647. Palindromic Substrings.md

File metadata and controls

54 lines (34 loc) · 1.04 KB

647. Palindromic Substrings

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

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".

Note:

  1. The input string length won't exceed 1000.

代码

class Solution:
    def countSubstrings(self, s: str) -> int:
        
        def helper(s, start, end):
            count = 0
            while start >= 0 and end < len(s) and s[start] == s[end]:
                count += 1
                start -= 1
                end += 1
            return count
        
        count = 0
        for i in range(len(s)):
            count += helper(s, i, i) + helper(s, i, i+1)
        return count