Member-only story

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:

  1. The expandAroundCenter function is used to find and count palindromic substrings around a given center. It increments the count variable for each palindromic substring found.
  2. The for loop iterates through each character in the input string s. For each character, it considers both odd and even length centers and expands around them using the expandAroundCenter function.
  3. 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")

https://leetcode.com/problems/palindromic-substrings/

--

--

Sonika | @Walmart | Frontend Developer | 11 Years
Sonika | @Walmart | Frontend Developer | 11 Years

No responses yet