字符串压缩(递归回调,内存消耗(比较耗时)最少的方法(内存击败100%))

image.png

本题采用递归回调整合新字符串方式处理
首先要注意一点:若“压缩”后的字符串没有变短,则返回原先的字符串
这句话可以直接理解成当新生成字符串<=2或着新生成字符串>=原始字符串,直接输出原始字符串即可

class Solution {
    public int count = 1, index = 0;
    public String newStr = "";
    public String compressString(String s) {
        // 当字符串长度小于2的时候直接返回字符串就行
        if (s.length() <= 2 ) {
            return s;
        }
        if ((index + 1) >= s.length()) {
            newStr += s.charAt(index);
            newStr += count;
            // 将长度判断放在这里是为了确保新生成的完整字符串的长度大于原始字符串
            if (newStr.length() >= s.length()) {
                return s;
            }
            return newStr;
        }
        if (s.charAt(index) != s.charAt(index + 1)) {
            newStr += s.charAt(index);
            newStr += count;
            count = 1;
            index++;
            return compressString(s);
        } else {
            count++;
            index++;
            return compressString(s);
        }   
    }
}

Leetcode链接:

https://leetcode-cn.com/problems/compress-string-lcci/solution/di-gui-hui-diao-nei-cun-xiao-hao-bi-jiao-hao-shi-z/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值