We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
One pass solution with backtracking, collecting all valid palindromes. Passes all tests.
def substrCount(n, s):
# print('---', s)
subs = []
for i, l in enumerate(s):
# collect all single chars
subs.append(l)
if i > 0:
# collect all substrings of same chars behind i
j = i - 1
sub = l
while j >= 0 and s[j] == l:
sub += s[j]
subs.append(sub)
j -= 1
# collect all substrings where middle char is different
# and all chars on left and right are the same
j = i - 1
if s[j] != l:
k = i + 1
sub = l
while j >= 0 and k < n and s[j] == s[k]:
if j+1 < i and s[j] != s[j+1]:
break
sub = f'{s[j]}{sub}{s[k]}'
subs.append(sub)
j -= 1
k += 1
# print(subs)
return len(subs)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Special String Again
You are viewing a single comment's thread. Return to all comments →
One pass solution with backtracking, collecting all valid palindromes. Passes all tests.