3163. String Compression III #790
-
Topics: Given a string
Return the string comp. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a greedy approach to compress the string by taking the longest possible prefix of repeating characters (up to 9 occurrences at a time) and then appending the length of the prefix along with the character to the result. Here's the step-by-step solution:
Let's implement this solution in PHP: 3163. String Compression III <?php
/**
* @param String $word
* @return String
*/
function compressString($word) {
$comp = "";
$i = 0;
$n = strlen($word);
while ($i < $n) {
$char = $word[$i];
$count = 0;
// Count the number of consecutive characters, but not more than 9
while ($i < $n && $word[$i] == $char && $count < 9) {
$count++;
$i++;
}
// Append the count and character to the compressed string
$comp .= $count . $char;
}
return $comp;
}
// Test cases
echo compressString("abcde"); // Output: "1a1b1c1d1e"
echo "\n";
echo compressString("aaaaaaaaaaaaaabb"); // Output: "9a5a2b"
?> Explanation:
Complexity Analysis
This solution is efficient and handles edge cases, such as sequences shorter than 9 characters or a single occurrence of each character. |
Beta Was this translation helpful? Give feedback.
We can use a greedy approach to compress the string by taking the longest possible prefix of repeating characters (up to 9 occurrences at a time) and then appending the length of the prefix along with the character to the result.
Here's the step-by-step solution:
Initialize Variables:
comp
(the compressed string) starts as an empty string.i
to track the position in theword
.Loop through
word
:word
, find the longest prefix of repeating characters that does not exceed 9 characters.Append to Compressed String: