How would you count the palindromic substrings in a string using the most straightforward method?
Enumerate every substring and test whether it reads the same forwards and backwards. For each start index, extend the end index and compare the substring with its reverse. Every palindrome is counted exactly once, because each substring has a unique pair of indices.
def count_palindromes(text):
total = 0
for i in range(len(text)):
for j in range(i, len(text)):
if text[i:j + 1] == text[i:j + 1][::-1]:
total += 1
return total
print(count_palindromes("abc"))
print(count_palindromes("aaa"))The outputs are 3 and 6. In abc the only palindromes are the three single characters. In aaa the palindromes are three single a characters, two substrings of length two, and one of length three, which is six in total.
The mechanism is a double loop over the n times n plus one over two substrings, and each test is itself linear because it builds a reversed copy and compares character by character. So the naive bound is cubic, and even the more careful version that compares characters in place from both ends towards the centre is quadratic.
The trade-off to name is that this version is fine for short strings and useless for long ones. It is also the easiest to get right, which is why it is worth writing first to make sure you understand the counting before optimising. The count itself has a useful closed form that helps you check your work: a string of n characters all of the same letter has n times n plus one over two palindromic substrings, and any string of n characters has at least n of them, one per character.