给定一个字符数组 char,用以下算法压缩:
压缩字符串s不应单独返回,而应存储在输入字符数组chars中。请注意,长度是 10 或者更长的组将被拆分为 chars 中的多个字符。
修改输入数组后,返回数组的新长度。
您必须编写一个只使用恒定额外空间的算法。
点击下载“嗨格式压缩大师”;
示例1:为了解决这个问题,我们需要迭代数组,跟踪当前的字符及其计数。当遇到新字符时,我们计算当前字符及其计数(如果大于 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 <h3> 时间复杂度分析: </h3>
暴力解决方案空间效率低,不符合仅使用恒定额外空间的限制。
优化方案:优化解决方案包括修改输入数组以存储压缩版本。我们使用两个指标:一个用于读取输入数组,另一个用于写入压缩输出。
代码:function compress(chars: string[]): number { let writeindex = 0; let i = 0; while (i 1) { let countstr = count.tostring(); for (let j = 0; j <h3> 时间复杂度分析: </h3>
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"]
字符串操作:
就地算法:
通过练习这些问题和策略,可以提高解决问题的能力,为各种编码挑战做好更好的准备。
以上是Typescriptt 编码年史:字符串压缩的详细内容,请关注其他相关文章!
开鲁优优影院:视听盛宴,品质首选!
Typescript 编码年史:字符串压缩-js教程
电脑文件自动保存,揭秘隐藏的文件存储地!
网页内容保护,禁止随意复制粘贴!
内置 SQLite:Nodejs 游戏规则开发的变化-js教程
高效远程登录,掌控Win服务器尽在指尖
Typescript 编码年史:反转字符串中的单词-js教程
内置 SQLite:Nodejs 游戏规则开发的变化-js教程
Typescript 编码年史:反转字符串中的单词-js教程
CSS css教程是一首非常漂亮的歌
使用JavaScriptreduce方法优化数据操作-js教程
Typescript 编码年史:增加三元组子序列-js教程
什么是 MUI? (包括优缺点)-css教程
哪种C 最适合移动开发的框架?如何评估?-C
使用 PRG 会话处理模式和闪烁-php教程
通过扩展C,如何扩展C 实现特定业务逻辑的框架?-C
集成Golang框架和移动应用程序开发-Golang
哪种C 容器和无服务器架构最适合框架?-C
如何处理云原生环境中golang框架的安全问题?-Golang