leetcode443

使用两个数组分别记录字符和对应的数字,然后清除原来的vector,重新向里面添加元素。注意判断1个字符时,不将'1'加入vector。

int compress(vector<char>& chars) {
    const int N = 1000;
    char words[N];//存储字符
    int count[N];//存储数字

    memset(words, ' ', sizeof(words));//count初始化为全' '
    memset(count, 0, sizeof(count));//count初始化为全0

    char lastChar = ' ';//ASCII:32    
    int i = 0;
    for (auto c : chars)
    {
        if (c != lastChar)//新字符
        {
            if (lastChar == ' ')
            {
                i = 0;
            }
            else
            {
                i++;
            }
        }
        words[i] = c;
        count[i]++;
        lastChar = c;
    }

    chars.clear();
    for (int j = 0; j <= i; j++)
    {
        chars.push_back(words[j]);
        int a = count[j];

        if (a == 1)
        {
            continue;
        }

        char str[4];
        sprintf(str, "%d", a);
        for (auto s : str)
        {
            if (s == '')
            {
                break;
            }
            chars.push_back(s);
        }
    }
    int sum = chars.size();
    return sum;
}
原文地址:https://www.cnblogs.com/asenyang/p/9700118.html