Leetcode 3163: String Compression III

grid47
grid47
Exploring patterns and algorithms
Dec 26, 2023 5 min read

You are given a string word. Compress the string using the following algorithm:

Begin with an empty string comp. While word is not empty, perform the following operation:

  1. Remove the longest prefix from word that consists of the same character repeating up to 9 times.
  2. Append the length of this prefix followed by the character to comp. Return the resulting string comp.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `word` that contains only lowercase English letters.
Example: Example 1: Input: word = "xyz" Output: "1x1y1z"
Constraints:
• 1 <= word.length <= 2 * 10^5
• word consists only of lowercase English letters.
Output: Return the string `comp` which is the compressed version of the input string `word`.
Example: Example 1: Input: word = "xyz" Output: "1x1y1z"
Constraints:
• The output will be a string.
Goal: The goal is to compress the string by iterating through it, identifying prefixes, and appending their length and character to the result.
Steps:
• Initialize an empty string `comp`.
• Iterate through the string `word`.
• For each group of consecutive identical characters (up to 9), append the length of the group followed by the character to `comp`.
• Return the resulting compressed string `comp`.
Goal: The input string must meet the following constraints.
Steps:
• 1 <= word.length <= 2 * 10^5
• word consists only of lowercase English letters.
Assumptions:
• The input string will not be empty.
• The input string contains only lowercase English letters.
Input: Example 1:
Explanation: For `word = "xyz"`, since there are no repeating characters, each character is treated as a separate group of length 1. Hence, the output is `"1x1y1z"`.

Input: Example 2:
Explanation: For `word = "aaaaaaaaaaaaaabb"`, we compress the string by grouping consecutive 'a's and 'b's. The first group has 9 'a's, the second has 5 'a's, and the last group has 2 'b's. Thus, the output is `"9a5a2b"`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus