String Compression III

medium string run-length encoding two pointers

Problem

Compress word into a string comp. While word is not empty, remove a maximum-length prefix made of a single character c repeating at most 9 times, then append the length of that prefix followed by c to comp. Return comp.

Inputword = "aaaaaaaaaaaaaabb"
Output"9a5a2b"
14 a’s split into runs of 9 and 5 (9 is the cap), then 2 b’s → "9a" + "5a" + "2b".

def compressedString(word):
    comp = []
    i, n = 0, len(word)
    while i < n:
        c = word[i]               # character of this run
        cnt = 0
        # extend while same char, capped at 9
        while i < n and word[i] == c and cnt < 9:
            cnt += 1
            i += 1
        comp.append(str(cnt))     # length of the prefix
        comp.append(c)            # the character
    return "".join(comp)
function compressedString(word) {
  let comp = "";
  let i = 0, n = word.length;
  while (i < n) {
    const c = word[i];            // character of this run
    let cnt = 0;
    // extend while same char, capped at 9
    while (i < n && word[i] === c && cnt < 9) {
      cnt++;
      i++;
    }
    comp += String(cnt) + c;      // count then character
  }
  return comp;
}
String compressedString(String word) {
    StringBuilder comp = new StringBuilder();
    int i = 0, n = word.length();
    while (i < n) {
        char c = word.charAt(i);  // character of this run
        int cnt = 0;
        // extend while same char, capped at 9
        while (i < n && word.charAt(i) == c && cnt < 9) {
            cnt++;
            i++;
        }
        comp.append(cnt).append(c);
    }
    return comp.toString();
}
string compressedString(string word) {
    string comp;
    int i = 0, n = word.size();
    while (i < n) {
        char c = word[i];         // character of this run
        int cnt = 0;
        // extend while same char, capped at 9
        while (i < n && word[i] == c && cnt < 9) {
            cnt++;
            i++;
        }
        comp += to_string(cnt) + c;
    }
    return comp;
}
Time: O(n) Space: O(n) for the output