
给定一个字符数组 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号