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
};
posted @ 2022-03-03 08:43  Cupid05  阅读(1115)  评论(0编辑  收藏  举报