LeetCode Solutions

443. String Compression

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int compress(vector<char>& chars) {
    int ans = 0;

    for (int i = 0; i < chars.size();) {
      const char letter = chars[i];
      int count = 0;
      while (i < chars.size() && chars[i] == letter) {
        ++count;
        ++i;
      }
      chars[ans++] = letter;
      if (count > 1)
        for (const char c : to_string(count))
          chars[ans++] = c;
    }

    return ans;
  }
};
			

class Solution {
  public int compress(char[] chars) {
    int ans = 0;

    for (int i = 0; i < chars.length;) {
      final char letter = chars[i];
      int count = 0;
      while (i < chars.length && chars[i] == letter) {
        ++count;
        ++i;
      }
      chars[ans++] = letter;
      if (count > 1)
        for (final char c : String.valueOf(count).toCharArray())
          chars[ans++] = c;
    }

    return ans;
  }
}
			

class Solution:
  def compress(self, chars: List[str]) -> int:
    ans = 0
    i = 0

    while i < len(chars):
      letter = chars[i]
      count = 0
      while i < len(chars) and chars[i] == letter:
        count += 1
        i += 1
      chars[ans] = letter
      ans += 1
      if count > 1:
        for c in str(count):
          chars[ans] = c
          ans += 1

    return ans