443. String Compression

Leetcode link

题目简介

/**
 * @param {character[]} chars
 * @return {number}
 */

题目给我们一个字符串数组 chars,要求我们把 chars 中重复的字符压缩成字符+出现次数的形式

要求在原数组中修改,并且返回新的数组的长度

解题思路

这题我们使用双指针的思路来做

慢指针 slow 负责出现在新字符的第一个位置,快指针负责寻找下一个新的字符

当快慢指针都找到对应的位置后,我们可以使用 fast - slow 来计算当前 slow 指针所在的字符有多少个

下一步我们使用 splice 替换 chars 的字符,然后更新快慢指针位置即可

Javascript

/**
 * @param {character[]} chars
 * @return {number}
 */
var compress = function (chars) {
    let fast = 0
    let slow = 0
    while (fast < chars.length) {
        if (chars[fast] === chars[slow]) {
            fast++
            continue
        }
        if (fast - slow > 1) {
            const count = `${fast - slow}`.split('')
            chars.splice(slow + 1, fast - slow - 1, ...count)
            slow += count.length + 1
            fast = slow
        } else {
            slow++
        }
    }
    if (fast - slow > 1) {
        const count = `${fast - slow}`.split('')
        chars.splice(slow + 1, fast - slow - 1, ...count)
        slow += count.length + 1
        fast = slow
    } else {
        slow++
    }

    return slow
};

results matching ""

    No results matching ""