javaScript 字符串压缩


字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

示例1:

输入:“aabcccccaaa”
输出:“a2b1c5a3”

来源:力扣(LeetCode)

/** * @param {string} S * @return {string} */
var compressString = function(S) {
   let nums = S.split("")
    let str = ''
    let i = 0
    while (i < nums.length) {
      let j = i + 1
      while (nums[i] == nums[j]) {
        j++
      }
      str = str + nums[i] + '' + (j - i)
      i = j
    }
    res =  str.length>=S.length?S:str
    return res
};


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM