Problem description:

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:

Use a variable count to calculate the total palindrome substring.
One thing to notice about palindrome string is that, the center of a palindrome string could be character or middle of two characters. Therefore, we need to check twice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def countSubstrings(self, s: str) -> int:
# use a subfunction to check palindromic
def palin(s, l, r):
count = 0
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
count += 1
return count

res = 0
for i in range(len(s)):
res += palin(s, i , i)
res += palin(s, i , i+1)
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int count= 0;
int countSubstrings(string s) {
int res= 0;
for(int i= 0; i< s.length(); i++){
expand(s, i, i);
expand(s, i, i+1);
}
return count;
}

void expand(string s, int left, int right){
while(left>= 0 && right < s.length() && s[left]==s[right]){
left--;
right++;
count++;
}
}
};

time complexity: $O(n^2)$
space complexity: O(1)
reference: