647. 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:
The input string length won’t exceed 1000.

Solution:

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def countSubstrings(self, s: str) -> int:
def isPalindromic(string):
return string == string[::-1]
ans = 0
for i in range(len(s)):
ans += 1
for j in range(1, i+1):
if isPalindromic(s[i-j: i+1]):
ans += 1
return ans

references

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×