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:
Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Β
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters.
Solutions
Solution 1: Expand Around Center
We can enumerate the center position of each palindrome and expand outward to count the number of palindromic substrings. For a string of length \(n\), there are \(2n-1\) possible center positions (covering both odd-length and even-length palindromes). For each center, we expand outward until the palindrome condition is no longer satisfied, and count the number of palindromic substrings.
The time complexity is \(O(n^2)\), where \(n\) is the length of string \(s\). The space complexity is \(O(1)\).
/** * @param {string} s * @return {number} */varcountSubstrings=function(s){letans=0;constn=s.length;for(letk=0;k<n*2-1;++k){leti=k>>1;letj=(k+1)>>1;while(~i&&j<n&&s[i]==s[j]){++ans;--i;++j;}}returnans;};
Solution 2: Manacher's Algorithm
In Manacher's algorithm, \(p[i] - 1\) represents the maximum palindrome length centered at position \(i\), and the number of palindromic substrings centered at position \(i\) is \(\left \lceil \frac{p[i]-1}{2} \right \rceil\).
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of string \(s\).