给定一个字符数组 chars,使用以下算法对其进行压缩:
压缩后的字符串s不应单独返回,而是存储在输入字符数组chars中。请注意,长度为 10 或更长的组将被拆分为 chars 中的多个字符。
修改输入数组后,返回数组的新长度。
您必须编写一个仅使用恒定额外空间的算法。
为了解决这个问题,我们需要迭代数组,同时跟踪当前字符及其计数。当遇到新字符时,我们将当前字符及其计数(如果大于 1)添加到数组中。我们需要确保这样做可以满足空间复杂性要求。
暴力解决方案涉及创建一个新数组来存储输入数组的压缩版本。这不节省空间,但可以帮助我们理解所涉及的步骤。
function compressBruteForce(chars: string[]): number { const n = chars.length; let compressed: string[] = []; let i = 0; while (i 1) { compressed.push(...count.toString().split('')); } } for (let j = 0; j时间复杂度分析:
暴力解决方案空间效率不高,并且不满足仅使用恒定额外空间的约束。
优化的解决方案涉及修改输入数组以存储压缩版本。我们使用两个指针:一个用于读取输入数组,一个用于写入压缩输出。
function compress(chars: string[]): number { let writeIndex = 0; let i = 0; while (i 1) { let countStr = count.toString(); for (let j = 0; j时间复杂度分析:
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"]
字符串操作:
就地算法:
通过练习此类问题和策略,您可以提高解决问题的能力,并为各种编码挑战做好更好的准备。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3