DDSA Solutions

3163. String Compression III

Time: O(n)
Space: O(n)

Problem Overview

String Compression III (Unknown) asks you to solve a structured algorithmic task. This is a common String pattern in coding interviews. Run-length encoding capping each run at 9; append count then character.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Run-length encoding capping each run at 9; append count then character.

Related patterns: String

3163.cs
C#
// Approach: Run-length encoding capping each run at 9; append count then character.
// Time: O(n) Space: O(n)

public class Solution
{
    public string CompressedString(string word)
    {
        int n = word.Length;
        StringBuilder sb = new StringBuilder();

        for (int i = 0, j = 0; i < n; i = j)
        {
            int count = 0;
            while (j < n && word[j] == word[i] && count < 9)
            {
                ++j;
                ++count;
            }
            sb.Append(count.ToString()).Append(word[i]);
        }

        return sb.ToString();
    }
}
Was this solution helpful?

Related Problems