【leetcode】【easy】【每日一题】面试题 01.06. Compress String LCCI

本文深入解析了一种基本的字符串压缩算法,该算法通过计算字符重复次数进行压缩。以aabcccccaaa为例,压缩后的结果为a2b1c5a3。文章详细介绍了算法的实现思路及代码实现,同时提供了LeetCode上的题目链接,帮助读者更好地理解和掌握字符串压缩的方法。

面试题 01.06. Compress String LCCI

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

Example 1:

Input: "aabcccccaaa"
Output: "a2b1c5a3"

Example 2:

Input: "abbccd"
Output: "abbccd"
Explanation: 
The compressed string is "a1b2c2d1", which is longer than the original string.

Note:

  1. 0 <= S.length <= 50000

题目链接:https://leetcode-cn.com/problems/compress-string-lcci/

 

思路

非常简单的题,模拟机器处理过程,一步一步做即可。

class Solution {
public:
    string compressString(string S) {
        int len = S.size();
        if(len==0) return S;
        string res = "";
        int cnt = 1;
        char ch = S[0];
        for(int i=1; i<len; ++i){
            if(S[i]==ch){
                ++cnt;
            }else{
                res += ( ch + to_string(cnt));
                ch = S[i];
                cnt = 1;
            }
        }
        res += (ch + to_string(cnt));
        return (res.size()<len)?res:S;
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值