【leetcode】443. String Compression

时间:2024-01-17 23:11:32

problem

443. String Compression

Input
["a","a","b","b","c","c","c"]
Output
["a","a","b","b","c","c"]
Expected
["a","","b","","c",""]

a:

Given an array of characters, compress it in-place.
After you are done modifying the input array in-place, return the new length of the array.

ss

Input
["a","a","a","b","b","a","a"]
Output
["a","","b",""]
Expected
["a","","b","","a",""]

ss

solution1:

class Solution {
public:
int compress(vector<char>& chars) {
if(chars.empty()) return ;
string res="";
char cur, pre;
int num = ;
for(int i=; i<chars.size(); i++)
{
cur = chars[i];
if(i==)
{
res += cur;
pre = cur;
} if(cur!=pre)
{
if(num>) res += to_string(num);//
res += cur;
pre = cur;
num = ;
}
else num++;
}
if(num>) res += to_string(num);
//
int len = ;
if(res.size()> chars.size()) len = chars.size();
else if(res.size()<=chars.size())
{
len = res.size();
for(int i=;i<res.size(); i++)
{
chars[i] = res[i];
} }
return len; }
};

参考

1. Leetcode_443. String Compression;