Perform run-length encoding on a string. Consecutive identical characters are replaced by the character followed by the count. For example, "aaabbc" becomes "a3b2c1".
Iterate through the string, tracking the current character and its count. When a different character is encountered, append the previous character and its count to the result, then start counting the new character.
Time complexity is O(n) and space is O(n) for the result. This is a lossless compression technique that works well for strings with many repeated consecutive characters.
Example Input & Output
Example 1
Input
"aaabbc"
Output
"a3b2c1"
Explanation
3 a's, 2 b's, 1 c
Example 2
Input
"aaa"
Output
"a3"
Explanation
All same
Example 3
Input
"abc"
Output
"a1b1c1"
Explanation
Each char appears once
Example 4
Input
""
Output
""
Explanation
Empty string
Example 5
Input
"a"
Output
"a1"
Explanation
Single char
Algorithm Flow

Recommendation Algorithm Flow for Run-Length Encoding
Solution Approach
Best Answers
java
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.
