← 返回 goldmansachs 的题目列表Count Palindromic Substrings
类型:qbank
Count the total number of palindromic substrings in the input string. The canonical "expand around center" interview problem; appears in Goldman's OA bank verbatim.
Requirements
Input: a string s.
Return: the total count of substrings of s that are palindromes. Each occurrence counts separately even if the substring content repeats.
public int palindromeCount(String s)
Notes
Expand-around-center is the standard answer: each of the 2n-1 centers (n single-character + n-1 between-character centers) is expanded outward while the characters match. O(n²) time, O(1) space.
Manacher's algorithm gives O(n) but is rarely necessary at Goldman — bring it up as an optimization only if pressed.
Edge cases: empty string returns 0; single character returns 1.
Preparation
Implement the two-pointer expand-around-center form and walk through "aaa" by hand: 6 palindromic substrings (a, a, a, aa, aa, aaa).
LC 647 "Palindromic Substrings" is the canonical equivalent; LC 5 "Longest Palindromic Substring" uses the same skeleton and is worth practicing alongside.