Skip to content

Example: Palindromic Substrings

Roberto Fronteddu edited this page Aug 1, 2024 · 2 revisions

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.

Solution

To count the number of palindromic substrings in a given string s, you can use the "Expand Around Center" technique. This approach involves expanding around each possible center of the palindrome and counting all the palindromic substrings.

Approach:

  • Expand Around Center: For each character and each pair of characters in the string, consider it as the center of a palindrome.
  • Expand: From each center, expand outwards as long as the characters on both sides are the same.
  • Count Palindromes: Increment the count for each valid palindrome found during the expansions.
public class Solution {
    public int countSubstrings(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            count += expandAroundCenter(s, i, i); // Count odd length palindromes
            count += expandAroundCenter(s, i, i + 1); // Count even length palindromes
        }
        return count;
    }

    private int expandAroundCenter(String s, int left, int right) {
        int count = 0;
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            count++;
            left--;
            right++;
        }
        return count;
    }
}
Clone this wiki locally