Special String Again

  • + 0 comments

    (hopefully) easy-to-read O(n) Python solution

    class Group(NamedTuple):
        char: str
        count: int
    
    def substrCount(n, s):
        total = 0
        groups = []
        group = Group(char=s[0], count=1)
    
        # iterate over 's', grouping runs of same char
        for char in s[1:]:
            if group.char == char:  # increment current char count
                group = Group(char=char, count=1 + group.count)
            else:  # register current group, restart count w/ new group
                groups.append(group)
                total += (group.count**2 + group.count) // 2  # n substrings
                group = Group(char=char, count=1)  # restart w/ new char
    
        # register final group
        groups.append(group)
        total += (group.count**2 + group.count) // 2  # n substrings in group
    
        # iterate over triplets of groups, counting
        # odd sized substrings w/ extra middle char
        for before, current, after in zip(groups, groups[1:], groups[2:]):
            if current.count == 1 and before.char == after.char:
                total += min(before.count, after.count)
    
        return total