647. Palindromic Substrings
Asked at 24Meta64Amazon41Microsoft39Apple35Bloomberg32Google31IBM55Goldman Sachs42Netskope100Pure Storage97Citadel95BNY Mellon65Akamai64Walmart Labs60HCL60Salesforce55Intuit52PayPal51Epic Systems51Anduril49Oracle49Cognizant48LinkedIn47Capital One35
Problem
Count the substrings of s that are palindromes; substrings at different positions count separately even if equal.
Example: "abc" → 3; "aaa" → 6
Constraints: length ≤ 1000.
Same centre expansion; every successful expansion step is one more palindrome.
Complexity: O(n²).
class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
for c in range(2 * len(s) - 1):
l, r = c // 2, (c + 1) // 2
while l >= 0 and r < len(s) and s[l] == s[r]:
count += 1
l, r = l - 1, r + 1
return count
assert Solution().countSubstrings("abc") == 3
assert Solution().countSubstrings("aaa") == 6
class Solution {
public int countSubstrings(String s) {
int count = 0;
for (int c = 0; c < 2 * s.length() - 1; c++)
for (int l = c / 2, r = (c + 1) / 2; l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r); l--, r++)
count++;
return count;
}
}
func countSubstrings(s string) int {
count := 0
for c := 0; c < 2*len(s)-1; c++ { // expand around each of the 2n-1 centres
l, r := c/2, (c+1)/2
for l >= 0 && r < len(s) && s[l] == s[r] {
count++
l, r = l-1, r+1
}
}
return count
}