LC 647 - Palindromic Substrings
LC 647 - Palindromic Substrings
Question
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
1
2
Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.
Example 2:
1
2
Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.
Constraints:
1 <= s.length <= 1000sconsists of lowercase English letters.
Links
Question here and solution here
Solution
concept
For the two pointer solution, it is quite similar to [[5. Longest Palindromic Substring]].
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def count_palin(self, s, l, r):
result = 0
while l >= 0 and r < len(s) and s[l] == s[r]:
result += 1
l -= 1
r += 1
return result
def countSubstrings(self, s: str) -> int:
result = 0
for i in range(len(s)):
l, r = i, i
result += self.count_palin(s, l, r)
l, r = i, i + 1
result += self.count_palin(s,l, r)
return result
Complexity
time: $O(n^2)$
space: $O(1)$
This post is licensed under CC BY 4.0 by the author.