Implement the stringCompressionLength method that returns the length after compressing consecutive repeated characters.

The input contains a string text. Your task is to return the length of the compressed version of the string.

Compression is based on consecutive repeated characters. For each group, write the character followed by how many times it appears. If the compressed version is not shorter than the original string, return the original string length instead.

For example, aabbccc becomes a2b2c3, so the compressed length is 6. For abc, compression would not reduce the string, so the answer remains 3.

Example 1

Input
text (string) = aaabbc
Returns (int) 6

Example 2

Input
text (string) = abc
Returns (int) 3

Example 3

Input
text (string) = aabbccc
Returns (int) 6

Scan the string from left to right and count consecutive occurrences of the same character.

Whenever the current group ends, add the length of the compressed group to a running total. A compressed group contains the character and its count, so aaa contributes the length of a3.

After calculating the compressed length, compare it with the original length. Return the smaller useful length so that the compression result never becomes longer than the original string.

Pseudocode:

function stringCompressionLength(text):
    if text is empty:
        return 0
    compressedLength = 0
    count = 1
    for i from 1 to length(text) - 1:
        if text[i] == text[i - 1]:
            count++
        else:
            compressedLength = compressedLength + 1 + numberOfDigits(count)
            count = 1
    compressedLength = compressedLength + 1 + numberOfDigits(count)
    return min(length(text), compressedLength)
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.