[leetcode]443. String Compression

本文介绍了一种原地压缩字符串的算法,通过遍历输入数组,将每个字符及其出现次数压缩存储,确保压缩后的数组长度不大于原数组。示例展示了如何将['a','a','b','b','c','c','c']压缩为['a','2','b','2','c','3'],并返回新数组的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array.

Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

分析:

原地压缩字符串,要求为每个字符只保留一个,后面为该字符原来出现的次数,最终返回新数组的长度。用变量cur来定位新数组中元素的位置,i来定位原数组中每个字符第一次出现的位置,j来记录每个字符出现的个数,转化为字符加入数组cur的后一位。

class Solution {
public:
    int compress(vector<char>& chars) {        
        int len = chars.size();
        int cur = 0;
        for(int i = 0 , j = 0; i < len; i = j)
        {
            while(j < len && chars[i] == chars[j])
                j++;
            chars[cur++] = chars[i];
            if(j - i == 1)
                continue;
            for(char c : to_string(j - i))
                chars[cur++] = c;               
        }
        return cur;               
    }
};

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值