力扣刷题日记-443.压缩字符串

54 阅读1分钟
  • 今天来朱提练手
  • 今天刷的是力扣第443题

题目:给你一个字符数组 chars ,请使用下述算法压缩:

从一个空字符串 s 开始。对于 chars 中的每组 连续重复字符 :

  • 如果这一组长度为 1 ,则将字符追加到 s 中。
  • 否则,需要向 s 追加字符,后跟这一组的长度。

压缩后得到的字符串 s 不应该直接返回 ,需要转储到字符数组 chars 中。需要注意的是,如果组长度为 10 或 10 以上,则在 chars 数组中会被拆分为多个字符。

请在 修改完输入数组后 ,返回该数组的新长度。

你必须设计并实现一个只使用常量额外空间的算法来解决此问题。

思路:

  • 双指针计算法

javascript版本

let compress = function(chars) {
    const n = chars.length;
    let write = 0,left = 0;
    for(let read = 0; read < n;read++){
        if(read === n - 1 || chars[read] !== chars[read+1]) {
            chars[write++] = chars[read]
            let num = read - left + 1;
            if(num>1) {
                const anchor = write
                while(num > 0) {
                    chars[write++] = '' + num % 10
                    num = Math.floor(num/10)
                }
                reverse(chars, anchor, write - 1)
            }
            left = read + 1
        }
    }
    return write
}
const reverse = (chars,left,right) => {
    while(left < right) {
        const temp = chars[left]
        chars[left] = chars[right]
        chars[right] = temp
        left++
        right--
    }
}