刷完上一道题目字符串压缩,看到leetcode中的443题,基本上与字符串压缩这道题一致。
class Solution {
public:
int compress(vector<char>& chars) {
int n = chars.size();
//location to write and character count
int loc = 0,cnt = 1;
if(n < 2) return n;
for(int i = 1 ;i < n ;i++)
{
if(chars[i] == chars[i-1])
{
cnt++;
}else{
chars[loc++] = chars[i-1];
if(cnt != 1)
{
string str_cnt = to_string(cnt);
for(auto c:str_cnt)
chars[loc++] = c;
}
cnt = 1;
}
//handle abbb and aaab case.
if(i == n -1)
{
chars[loc++] = chars[i];
if(cnt != 1){
string str_cnt = to_string(cnt);
for(auto c:str_cnt)
chars[loc++] = c;
}
}
}
return loc;
}
};
运行效率:
Runtime: 4 ms, faster than 92.64% of C++ online submissions for String Compression.
Memory Usage: 8.8 MB, less than 78.60% of C++ online submissions for String Compression.
看了讨论区大神的解法非常的精炼,AC代码如下:
class Solution {
public:
int compress(vector<char>& chars) {
int n = chars.size();
if(n < 2) return n;
//i represent the start of a character,loc resprenet where to write
int i = 0,loc = 0;
for(int j = 0;j < n;j++)
{
if(j == n-1 || chars[j] != chars[j+1])
{
chars[loc++] = chars[j];
//skip length== 1 case
if(i < j)
{
//j - i + 1 > 1,represent the character count
for(auto c:to_string(j - i + 1))
chars[loc++] = c;
}
//update start position
i = j + 1;
}
}
return loc;
}
};