跳到主要内容

443.压缩字符串

链接:443.压缩字符串
难度:Medium
标签:双指针、字符串
简介:给你一个字符数组 chars ,请在 修改完输入数组后 ,返回该数组的新长度。

题解 1 - typescript

  • 编辑时间:2021-08-21
  • 执行用时:84ms
  • 内存消耗:40.2MB
  • 编程语言:typescript
  • 解法介绍:双指针。
function compress(chars: string[]): number {
let pos = 0;
const n = chars.length;
for (let i = 0; i < n; ) {
const c = chars[i];
let count = 1;
while (i + count < n && chars[i + count] === c) count++;
i += count;
chars[pos++] = c;
if (count > 1) {
let countStr = '';
while (count) {
countStr = (count % 10) + countStr;
count = ~~(count / 10);
}
for (const c of countStr) chars[pos++] = c;
}
}
return pos;
}