Special String Again

  • + 0 comments

    I use a deque to keep track of previous counts to find the middle cases. I like this solution because there is a single loop while most other solutions have nested loops.

    from collections import deque
    
    # Complete the substrCount function below.
    def substrCount(n, s):
        current_char = None
        total_count = 0
        char_count = 0
        count_deque = deque([0, 0], maxlen=2)
    
        for i in range(n):
            if s[i] == current_char:
                char_count += 1
            else:
                # check for middle chars
                if i >=3 and count_deque[1] == 1 and s[i-2-char_count] == current_char:
                    
                    middle_case_count = min([count_deque[0], char_count])
                    total_count += middle_case_count
                total_count += sum(range(char_count+1))
                count_deque.append(char_count)
                current_char = s[i]
                char_count = 1
                
        if i >=3 and count_deque[1] == 1 and s[i-1-char_count] == current_char:
            middle_case_count = min([count_deque[0], char_count])
            total_count += middle_case_count
        total_count += sum(range(char_count+1))
        return total_count