Special String Again

  • + 0 comments

    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)