字符串壓縮。利用字符重復出現的次數,編寫一種方法,實現基本的字符串壓縮功能。比如,字符串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
};
