欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]443. String Compression

程序员文章站 2024-03-13 22:13:04
...

[leetcode]443. String Compression


Analysis

everyday is the first day of your rest life—— [间歇性迷茫+2~]

Given an array of characters, compress it in-place.
压缩字符串,基本上看样例就能明白意思了。

Implement

class Solution {
public:
    int compress(vector<char>& chars) {
        if(chars.size() == 0)
            return 0;
        int len = chars.size();
        int cnt = 1;
        int res = 1;
        char t = chars[0];
        for(int i=1; i<len; i++){
            if(chars[i] == t)
                cnt++;
            else{
                if(cnt > 1){
                    string s = to_string(cnt);
                    for(auto c:s)
                        chars[res++] = c;
                }
                cnt = 1;
                t = chars[i];
                chars[res++] = t;
            }
        }
        if(cnt > 1){
            string s = to_string(cnt);
            for(auto c:s)
                chars[res++] = c;
        }
        chars.resize(res);
        return res;
    }
};
相关标签: leetcode