Skip to content

3163. String Compression III #790

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can use a greedy approach to compress the string by taking the longest possible prefix of repeating characters (up to 9 occurrences at a time) and then appending the length of the prefix along with the character to the result.

Here's the step-by-step solution:

  1. Initialize Variables:

    • comp (the compressed string) starts as an empty string.
    • Use a pointer or index i to track the position in the word.
  2. Loop through word:

    • While there are characters left in word, find the longest prefix of repeating characters that does not exceed 9 characters.
    • Count how many times the current character repeats consecutively, up to a maximum of 9.
  3. Append to Compressed String:

    • Append the count followe…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Nov 4, 2024
Maintainer Author

You must be logged in to vote
2 replies
@topugit
Comment options

topugit Nov 4, 2024
Collaborator

@topugit
Comment options

topugit Nov 4, 2024
Collaborator

Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants