G - Pre-Palindrome Editorial by en_translator
First, we will count the number of odd-length good strings.
We consider all positions for the middle character of a good string. Fix the position to the \(i\)=th character.
A string whose middle is at the \(i\)-the character and length is \((2k+1)\) is a good string if and only if there are at most one index \(j=1,2,\ldots,k\) such that \(S_{i-j}\neq S_{i+j}\). Therefore, we may iterate \(k\) in ascending order to check if there are at most one index \(1\le j\le k\) such that \(S_{i-j}\neq S_{i+j}\).
Even-length good strings can be counted likewise.
The problem can be solved by appropriately implementing this idea. The complexity is \(O(N^2)\).
s = input()
n = len(s)
ans = 0
for k in range(2):
for st in range(n):
l, r = st - k, st
cnt = 0
while 0 <= l and r < n:
if s[l] != s[r]:
cnt += 1
if cnt == 2:
break
l -= 1
r += 1
ans += 1
print(ans)
Bonus: solve the problem under \(|S| \le 10^5\).
posted:
last update: