|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 3163. String Compression III |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/string-compression-iii/description/ |
| 6 | + |
| 7 | +=begin |
| 8 | +Given a string word, compress it using the following algorithm: |
| 9 | +* Begin with an empty string comp. While word is not empty, use the following operation: |
| 10 | + * Remove a maximum length prefix of word made of a single character c repeating at most 9 times. |
| 11 | + * Append the length of the prefix followed by c to comp. |
| 12 | +Return the string comp. |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +Input: word = "abcde" |
| 16 | +Output: "1a1b1c1d1e" |
| 17 | +Explanation: |
| 18 | +Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation. |
| 19 | +For each prefix, append "1" followed by the character to comp. |
| 20 | +
|
| 21 | +Example 2: |
| 22 | +Input: word = "aaaaaaaaaaaaaabb" |
| 23 | +Output: "9a5a2b" |
| 24 | +Explanation: |
| 25 | +Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation. |
| 26 | +* For prefix "aaaaaaaaa", append "9" followed by "a" to comp. |
| 27 | +* For prefix "aaaaa", append "5" followed by "a" to comp. |
| 28 | +* For prefix "bb", append "2" followed by "b" to comp. |
| 29 | +
|
| 30 | +Constraints: |
| 31 | +* 1 <= word.length <= 2 * 105 |
| 32 | +* word consists only of lowercase English letters. |
| 33 | +=end |
| 34 | + |
| 35 | +# @param {String} word |
| 36 | +# @return {String} |
| 37 | +def compressed_string(word) |
| 38 | + word.gsub(/(.)\1{,8}/) { _1.size.to_s + $1 } |
| 39 | +end |
| 40 | + |
| 41 | +# **************** # |
| 42 | +# TEST # |
| 43 | +# **************** # |
| 44 | + |
| 45 | +require "test/unit" |
| 46 | +class Test_compressed_string < Test::Unit::TestCase |
| 47 | + def test_ |
| 48 | + assert_equal "1a1b1c1d1e", compressed_string("abcde") |
| 49 | + assert_equal "9a5a2b", compressed_string("aaaaaaaaaaaaaabb") |
| 50 | + end |
| 51 | +end |
0 commit comments