By Aamna Alam
In this Java tutorial, we will see run-length encoding. It is a form of data compression in which data(input) characters are stored and counted.
Run-length encoding (RLE) is a concept in which we take long data string as inputs and compress it in a manner(by counting the number of times a character is present and write that number with the characters) to reduce the number of bits in data.
CONCEPT BEHIND THE PROBLEM:
In this problem, long-run data is any sequence of alphabets, special characters or numbers which we encode and then print. For example, for the input 'ABBBD' we will be getting the output as 1A3B1D. At the same time, we cannot encode very long-run data naively as the counted characters but in a split manner, for example: 'BBBBBBBBBBBBBBBBBBBBCCC' should not be as 20B3C but as 9B9B2B3C to be decode properly.
example, Input String1: AAAABBBBBBBBBBBBBCCCDD
Output String1: 4A9B4B3C2D
1)Create a new empty string.
2)Pick the characters from the string one by one by using for loop.
3)Check and count the occurrence of the picked character in the whole string.
4)If the occurrence of the picked character is greater than 9, append the picked character with 9 to the new empty string(ns = ns+"9"+ch)and again make the counter value(c=1) for very long-run data exceeding(character repeating beyond 19).
5)If the occurrence of the picked character is less than equal to 9, append the picked character with the occurrence number(frequency) to the new empty string(ns = ns+Integer.toString(c)+ch).
6)else append the picked character with 9 and (occurrence-9) to the new empty string.( ns = ns+"9"+ch+Integer.toString(c-9)+ch).
7)Print the newly formed string.