The task is to count the number of substrings in a palindromic string.
The boilerplate code
function countPalindromicSubstr(str) {
// your code here
}
Each palindrome has a center. There are two kinds of centers: one with a single character(for odd-length palindromes), and a gap between 2 characters(for even-length palindromes).
For each center, we look left and right at the same time. If both characters match, it's a palindrome. Count it, move one step further out on both sides and keep going until the characters stop matching or the end of the string is reached.
let count = 0;
function expand(left, right) {
while (left >= 0 && right < str.length && str[left] === str[right]) {
count++;
left--;
right++;
}
}
Repeat for every possible center
for (let i = 0; i < str.length; i++) {
expand(i, i);
expand(i, i + 1);
}
The final code
function countPalindromicSubstr(str) {
// your code here
let count = 0;
function expand(left, right) {
while(left >= 0 && right < str.length && str[left] === str[right]) {
count++;
left--;
right++;
}
}
for(let i = 0; i < str.length; i++) {
expand(i, i);
expand(i, i + 1);
}
return count;
}
That's all folks!
Top comments (0)