压缩字符串

<script>
    //取出字符串,判断重复停止,添加到新字符串中
    function solution(str) {
        if(typeof str !== "string"){//类型不为字符串返回空
            return '';
        }
        if (str.length <= 1){//直接返回源字符串
            return str;
        }
        let newStr = '';
        let s = str.charAt(0);
        let num = 1; //跳过第一个
        let total = str.length;
        for (let i = 1; i < total; i++) {
            let nowS = str.charAt(i);
            if (nowS === s) {
                num = num + 1; // 增加数量
                if (i + 1 === total) {
                    newStr += `${s}${num}`; // 遍历结束时,拼接最后的字符串
                }
            } else {
                newStr += `${s}${num}`; // 拼接字符串
                num = 1; // 重置为1
                s = nowS; // 转为下一个字符s
            }
        }
        if (newStr.length >= str.length) {// 生成的字符串长度大于等于源字符串 返回源字符串 否则返回生成的字符串
            return str;
        } else {
            return newStr;
        }
    };

    console.log(
        '输出:',
        solution('aabcccccaaa'), // a2b1c5a3
        solution('aabbcc'), // aabbcc
        solution('aaaa'), // a4
        solution('a'), // a
        solution('') // ''
    );

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值