给定一个字符数组 char,使用以下算法对其进行压缩:
压缩后的字符串 s 不应单独返回,而是存储在输入字符数组 chars 中。请注意,长度为 10 或更长的组将被拆分为 chars 中的多个字符。
修改完输入数组后,返回数组的新长度。
您必须编写一个仅使用恒定额外空间的算法。
为了解决这个问题,我们需要迭代数组,同时跟踪当前字符及其计数。当遇到新字符时,我们将当前字符及其计数(如果大于 1)添加到数组中。我们需要确保这样做能够满足空间复杂度要求。
暴力解决方案涉及创建一个新数组来存储输入数组的压缩版本。这不节省空间,但可以帮助我们理解所涉及的步骤。
function compressBruteForce(chars: string[]): number { const n = chars.length; let compressed: string[] = []; let i = 0; while (i < n) { let char = chars[i]; let count = 0; while (i < n && chars[i] === char) { i++; count++; } compressed.push(char); if (count > 1) { compressed.push(...count.toString().split('')); } } for (let j = 0; j < compressed.length; j++) { chars[j] = compressed[j]; } return compressed.length; }
暴力解决方案空间利用率不高,并且不满足仅使用恒定额外空间的约束。
优化的解决方案涉及修改输入数组以存储压缩版本。我们使用两个指针:一个用于读取输入数组,一个用于写入压缩输出。
function compress(chars: string[]): number { let writeIndex = 0; let i = 0; while (i < chars.length) { let char = chars[i]; let count = 0; // Count the number of consecutive repeating characters while (i < chars.length && chars[i] === char) { i++; count++; } // Write the character chars[writeIndex] = char; writeIndex++; // Write the count if greater than 1 if (count > 1) { let countStr = count.toString(); for (let j = 0; j < countStr.length; j++) { chars[writeIndex] = countStr[j]; writeIndex++; } } } return writeIndex; }
console.log(compressBruteForce(["a","a","b","b","c","c","c"])); // 6, ["a","2","b","2","c","3"] console.log(compressBruteForce(["a"])); // 1, ["a"] console.log(compressBruteForce(["a","b","b","b","b","b","b","b","b","b","b","b","b"])); // 4, ["a","b","1","2"] console.log(compressBruteForce(["a","a","a","a","a","a","a","a","a","a"])); // 3, ["a","1","0"] console.log(compressBruteForce(["a","b","c"])); // 3, ["a","b","c"] console.log(compress(["a","a","b","b","c","c","c"])); // 6, ["a","2","b","2","c","3"] console.log(compress(["a"])); // 1, ["a"] console.log(compress(["a","b","b","b","b","b","b","b","b","b","b","b","b"])); // 4, ["a","b","1","2"] console.log(compress(["a","a","a","a","a","a","a","a","a","a"])); // 3, ["a","1","0"] console.log(compress(["a","b","c"])); // 3, ["a","b","c"]
字符串操作:
就地算法:
通过练习这些问题和策略,您可以提高解决问题的能力,并为各种编码挑战做好更好的准备。
以上是Typescript 编码编年史:字符串压缩的详细内容。更多信息请关注PHP中文网其他相关文章!