Search code examples
c#linqrun-length-encoding

Run-length encoding of a given sorted string


Write code for run -length encoding of a given string
Sample Input: aaaaaaaaaabcccccc
Output: a10bc6

My code:

static void Main(string[] args)
{
    string str = "aaaaaaaaaabcccccc";
    var qry = (from c in str
               group c by c into grp
               select new
               {
                   output = grp.Key.ToString() + grp.Count().ToString()
               });
    StringBuilder sb = new StringBuilder();
    foreach (var item in qry)
    {
        sb.Append(item.output);
    }
    Console.WriteLine(sb.ToString());
    Console.ReadLine();
}

However it returns:

a10b1c6

I want to remove the count for non-repeating char, here is "1" for letter 'b'.

Assume that it is a sorted string.


Solution

  • Here's a simplified version:

    public static void Main()
    {
       string str = "aaaaaaaaaabcccccc";
        var qry = (from c in str
                   group c by c into grp
                   let c = grp.Count()
                   select grp.Key.ToString() + (c > 1 ? c.ToString() : ""));
    
        Console.WriteLine(string.Join("",qry));
        Console.ReadLine();
    }
    

    You need to be careful with the bracket placement around the ternary expression, and then I used string.Join to avoid the mess with a for each loop and string builder.