Leetcode 443 Solution
This article provides solution to leetcode question 443 (string-compression)
Access this page by simply typing in "lcs 443" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/string-compression
Solution
class Solution {
public:
int compress(vector<char>& chars) {
int tail = 0;
char last_char = 0;
int last_count = 0;
for (int i = 0; i < chars.size(); i++)
{
char ch = chars[i];
if (last_char == ch)
last_count++;
else
{
if (last_char)
chars[tail++] = last_char;
if (last_count > 1)
{
string last_count_str = to_string(last_count);
for (auto ch : last_count_str)
chars[tail++] = ch;
}
last_char = ch;
last_count = 1;
}
}
if (last_char)
chars[tail++] = last_char;
if (last_count > 1)
{
string last_count_str = to_string(last_count);
for (auto ch : last_count_str)
chars[tail++] = ch;
}
return tail;
}
};