File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 647. Palindromic Substrings
3+ https://leetcode.com/problems/palindromic-substrings/
4+
5+ Solution:
6+ To solve this problem, we can use the expand from center technique.
7+ We can iterate through each character in the string and expand from the center to find palindromic substrings.
8+ We can handle both odd and even length palindromes by expanding from the center and center + 1.
9+ We keep track of the number of palindromic substrings found.
10+ The total number of palindromic substrings is the sum of palindromic substrings found at each character.
11+
12+ Time complexity: O(n^2)
13+ - We iterate through each character in the string.
14+ - For each character, we expand from the center to find palindromic substrings.
15+ - The time complexity is O(n^2) due to the nested loops.
16+
17+ Space complexity: O(1)
18+ - We use constant space to store variables.
19+ - The space complexity is O(1).
20+ """
21+
22+
23+ class Solution :
24+ def countSubstrings (self , s : str ) -> int :
25+ num_pal_strs = 0
26+
27+ def expand_from_center (left , right ):
28+ num_pal = 0
29+ while left >= 0 and right < len (s ) and s [left ] == s [right ]:
30+ left -= 1
31+ right += 1
32+ num_pal += 1
33+ return num_pal
34+
35+ for i in range (len (s )):
36+ num_pal_strs += expand_from_center (i , i )
37+ num_pal_strs += expand_from_center (i , i + 1 )
38+
39+ return num_pal_strs
You can’t perform that action at this time.
0 commit comments