Given a string, perform run-length encoding: replace consecutive repeated characters with the character followed by the count. For example, "aaabbc" becomes "a3b2c1". If a character appears only once, include it with a count of 1.
For example, encoding "hello" produces "h1e1l2o1". Encoding "aabbbcc" produces "a2b3c2". An empty string returns "". A single character "x" returns "x1".
Run-length encoding is a simple form of data compression. It replaces repeated characters with a count, reducing storage for data with long runs of identical values. It is used in bitmap image compression (BMP, PCX) and as a building block for more advanced compression algorithms.
The solution iterates through the string, counting consecutive occurrences of each character. When the character changes or the end is reached, append the character and its count to the result.
Edge cases include an empty string (return ""), a string with all unique characters (each followed by "1"), and a string with a single character repeated many times.
Example Input & Output
3 a's, 2 b's, 1 c
All same
Each char appears once
Empty string
Single char
Algorithm Flow
Solution Approach
Iterate through the string, counting consecutive identical characters and appending each with its count.
Handle empty string. Start with count = 1 for the first character. Loop from index 1: if the current character matches the previous, increment count. Otherwise, append the previous character and its count to the result, then reset count to 1. After the loop, append the last character and its final count.
Time complexity is O(n), space complexity is O(n) for the result.
Best Answers
class Solution {
public String solution(String s) {
if(s.isEmpty())return"";StringBuilder r=new StringBuilder();int c=1;
for(int i=1;i<=s.length();i++){
if(i<s.length()&&s.charAt(i)==s.charAt(i-1))c++;
else{r.append(s.charAt(i-1)).append(c);c=1;}
}return r.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
