↻one more pass.
Strings · Medium

Palindromic Substrings: the idea to remember.

Count palindromic substrings, treating equal text at different positions as separate occurrences.

Solve on LeetCode ↗

The core insight

Expand at every character center and gap center. Count every successful matching expansion.

Why it works

Each substring palindrome has a unique center and radius, so successful expansions count each occurrence exactly once.

The mistake to avoid

Do not deduplicate equal strings: the three single characters in aaa are three separate occurrences.

Time: O(n²)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int countSubstrings(String s) {
    int total = 0;
    for (int center = 0; center < 2 * s.length() - 1; center++) {
        int l = center / 2, r = l + center % 2;
        while (l >= 0 && r < s.length() && s.charAt(l--) == s.charAt(r++)) total++;
    }
    return total;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.