使用两个数组分别记录字符和对应的数字,然后清除原来的vector,重新向里面添加元素。注意判断1个字符时,不将'1'加入vector。
int compress(vector<char>& chars) {
const int N = ;
char words[N];//存储字符
int count[N];//存储数字 memset(words, ' ', sizeof(words));//count初始化为全' '
memset(count, , sizeof(count));//count初始化为全0 char lastChar = ' ';//ASCII:32
int i = ;
for (auto c : chars)
{
if (c != lastChar)//新字符
{
if (lastChar == ' ')
{
i = ;
}
else
{
i++;
}
}
words[i] = c;
count[i]++;
lastChar = c;
} chars.clear();
for (int j = ; j <= i; j++)
{
chars.push_back(words[j]);
int a = count[j]; if (a == )
{
continue;
} char str[];
sprintf(str, "%d", a);
for (auto s : str)
{
if (s == '\0')
{
break;
}
chars.push_back(s);
}
}
int sum = chars.size();
return sum;
}