Skip to content

3163. String Compression III 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  string compressedString(string word) {
    const int n = word.length();
    string ans;

    for (int i = 0, j = 0; i < n; i = j) {
      int count = 0;
      while (j < n && word[j] == word[i] && count < 9) {
        ++j;
        ++count;
      }
      ans += to_string(count) + word[i];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public String compressedString(String word) {
    final 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.charAt(j) == word.charAt(i) && count < 9) {
        ++j;
        ++count;
      }
      sb.append(String.valueOf(count)).append(word.charAt(i));
    }

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def compressedString(self, word: str) -> str:
    n = len(word)
    ans = []
    i = 0
    j = 0

    while i < n:
      count = 0
      while j < n and word[j] == word[i] and count < 9:
        j += 1
        count += 1
      ans.append(str(count) + word[i])
      i = j

    return ''.join(ans)