Member-only story
Palindromic Substrings | DP | 1D |
1 min readAug 15, 2023
Before starting this problem, look into Longest Palindromic Substring solution
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".
Implementation,
In this method:
- The
expandAroundCenter
function is used to find and count palindromic substrings around a given center. It increments thecount
variable for each palindromic substring found. - The
for
loop iterates through each character in the input strings
. For each character, it considers both odd and even length centers and expands around them using theexpandAroundCenter
function. - Finally, the method returns the total count of palindromic substrings found in the input string.
Remember that this solution uses the same expanding technique as in the previous examples, but instead of keeping track of the longest palindrome, it increments the count
for each palindrome encountered.
function countSubstrings(s) {
let count = 0;
function expandAroundCenter(left, right) {
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++; // Increment count for each palindromic substring found
left--;
right++;
}
}
for (let i = 0; i < s.length; i++) {
// For odd-length palindromes
expandAroundCenter(i, i);
// For even-length palindromes
expandAroundCenter(i, i + 1);
}
return count;
}
const input = "abc";
console.log(countSubstrings(input)); // Output: 3 ("a", "b", "c")