gopetoamg
gopetoamg

Reputation: 19

How to find the longest block of exact same chars in a string?

Read from the standard input:

string to search in -> hoopla

Print to the standard output:

One line of output - the first block with maximum lenght in the given array -> oo please note that different case matters.

Sample Tests Input: hoopa Output: oo

Input: abbCCCcddBBBxx Output: CCC

Thank you in advance !

Upvotes: 0

Views: 320

Answers (1)

Leo
Leo

Reputation: 1303

You can get the longest block in a string like this. It iterates over the string so the runtime should increase only linearly as the input length increases.

def get_longest_block(text):
    char = None
    amount = 0

    maxChar = None
    maxAmount = 0

    for c in text:
        if c == char:
            amount += 1
        else:
            if amount > maxAmount:
                maxChar = char
                maxAmount = amount
            amount = 1
        char = c

    return maxChar * maxAmount

print(get_longest_block("hoopla"))
print(get_longest_block("abbCCCcddBBBxx"))

Upvotes: 2

Related Questions