Sobes.tech
Principal

/** * Repeating characters * * Write a function that takes a string as input and returns * for each unique character the maximum number of its consecutive repetitions. * * Input: aaffbaaaaffc * Output: a:4 b:1 f:2 c:1 * * Input: bbbbbb * Output: b:6 * * Input: abc * Output: a:1 b:1 c:1 * * Input: aabbcc * Output: a:2 b:2 c:2 * * Input: aaabbbccc * Output: a:3 b:3 c:3 * * Input: a * Output: a:1 * * Input: "" * Output: */

sobes.tech AI

Answer from AI

Below is an example of a Python function that calculates the maximum number of consecutive repetitions for each unique letter in a string:

def max_consecutive_repeats(s):
    if not s:
        return ""

    result = {}
    current_char = s[0]
    current_count = 1

    for char in s[1:]:
        if char == current_char:
            current_count += 1
        else:
            # Update the maximum for the previous character
            if current_char not in result or current_count > result[current_char]:
                result[current_char] = current_count
            current_char = char
            current_count = 1

    # Update for the last character
    if current_char not in result or current_count > result[current_char]:
        result[current_char] = current_count

    # Form the output string
    return ' '.join(f"{char}:{count}" for char, count in sorted(result.items()))

# Usage examples
print(max_consecutive_repeats("aaffbaaaaffc"))  # a:4 b:1 c:1 f:2
print(max_consecutive_repeats("bbbbbb"))         # b:6
print(max_consecutive_repeats("abc"))            # a:1 b:1 c:1
print(max_consecutive_repeats("aabbcc"))         # a:2 b:2 c:2
print(max_consecutive_repeats("aaabbbccc"))      # a:3 b:3 c:3
print(max_consecutive_repeats("a"))              # a:1
print(max_consecutive_repeats("") )              # (empty string)