← All problems

3163. String Compression III

MediumOpen on LeetCodeProblem statement

Problem Statement

3163. String Compression III

Medium


Given a string word, compress it using the following algorithm:

Return the string comp.

 

Example 1:

Input: word = "abcde"

Output: "1a1b1c1d1e"

Explanation:

Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.

For each prefix, append "1" followed by the character to comp.

Example 2:

Input: word = "aaaaaaaaaaaaaabb"

Output: "9a5a2b"

Explanation:

Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.

 

Constraints:

Java

Source file
class Solution {
    public String compressedString(String word) {
        word += '.'; // EOF
        StringBuilder sb = new StringBuilder();
        char prev = word.charAt(0);
        int count = 0;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (count == 9 || c != prev) {
                sb.append(count).append(prev);
                prev = c;
                count = 1;
            } else
                count++;
        }
        return sb.toString();
    }
}