Leetcode 443. String Compression
Given an array of characters chars
, compress it in-place such that the length of the compressed string is reduced. The compression algorithm should use the following rules:
chars[i]...chars[j]
, it should be replaced by chars[i]
followed by the number of consecutive characters if the group length is greater than 1.chars = ['a','a','b','b','c','c','c']
['a','2','b','2','c','3']
Q: What is the maximum length of the input array chars
?
A: You can assume chars
has length at most 2000.
Q: Should the characters in the array be only lowercase alphabets? A: The problem doesn’t specify a restriction, so let’s assume it can be any valid character.
Q: Is it necessary to use O(1) extra space? A: Yes, the modification should be done in-place with O(1) extra space.
read
and the other for writing write
.chars
array with the read
pointer to identify groups of repeated characters.write
pointer.#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int compress(vector<char>& chars) {
int write = 0, read = 0;
int n = chars.size();
while (read < n) {
char currentChar = chars[read];
int count = 0;
// Count the number of consecutive characters
while (read < n && chars[read] == currentChar) {
read++;
count++;
}
// Write the character
chars[write++] = currentChar;
// Write the count if more than 1
if (count > 1) {
for (char c : to_string(count)) {
chars[write++] = c;
}
}
}
return write;
}
};
while (read < n)
: Iterate through the array until the end.char currentChar = chars[read]
: Store the current character.while (read < n && chars[read] == currentChar)
: Count the number of consecutive occurrences of currentChar
.chars[write++] = currentChar
: Write the current character to the write
position and increment write
.if (count > 1)
: If the count of consecutive characters is more than 1, convert the count to a string, and then write each digit to the write
position.write
, which stores the new length of the compressed array.n
is the length of the chars
array. This is because we traverse the array a constant number of times (each element is visited once).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?