Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs: for example, simple graphic images such as icons, line drawings, and animations. It is not useful with files that don’t have many runs as it could greatly increase the file size.

  /// <summary>
        /// Given AAABBGFF should get an output 3{A} 2{B}1{G}2{F}
        /// http://en.wikipedia.org/wiki/Run-length_encoding
        /// </summary>
        /// <param name="input"></param>
        public static void RIL(string input)
        {
            Console.Write(input + " : " );
            StringBuilder output = new StringBuilder();
            int charCount = 0;
            var inputChars = input.ToCharArray();
            char currentChar, nextChar;
            currentChar = nextChar = inputChars[0];

            for (int i = 0; i < inputChars.Length; i++)
            {
                currentChar = inputChars[i];
                if (i + 1 < inputChars.Length)
                {
                   
                    nextChar = inputChars[i + 1];
                }
                if (currentChar  != nextChar )
                {

                    output.Append(charCount + 1);
                    output.Append("{");
                    output.Append(currentChar);
                    output.Append("}");
                    charCount = 0;
                
                }
                else {
                    charCount++;
                }
            }
            output.Append(charCount );
            output.Append("{");
            output.Append(currentChar);
            output.Append("}");
            
            Console.Write(output.ToString());
            Console.WriteLine();

        }

Test Cases

  1. AAABBGFF : 3{A}2{B}1{G}2{F}
  2. WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWW WWWWWWBWWWWWWWWWWWWWW : 12{W}1{B}12{W}3{B}24{W}1{B}14{W}
  3. AAABBGGGGGGGGFFXXXXXXTTTTTyyyyyyvvvvv : 3{A}2{B}8{G}2{F}6{X}5{T}6{y}5{v}
  4. AAAABBCCCCCCCBBCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD :

    4{A}2{B}7{C}2{B}4{C}38{D}