Skip to main content
4 of 5
deleted 619 characters in body
t3chb0t
  • 44.7k
  • 9
  • 84
  • 191

Apart from other reviews I show you an alternative how you can make this really short with LINQ and Regex:

OK, the first solution wasn't perfect. This one will however can do it correctly:

var alphabet = Enumerable.Range(97, 26).Select (i => (char)i + "+");
var pattern = "(" + string.Join("|", alphabet) + ")";

var compressed2 =
    Regex.Matches(str, pattern)
    .Cast<Match>().Select (m => new 
    { 
        Char = m.Groups[1].Value[0], 
        Count = m.Groups[1].Value.Length 
    })
    .Aggregate (string.Empty, (result, nextGroup)  => 
        result.ToString() 
        + nextGroup.Char 
        + (nextGroup.Count > 1 ? nextGroup.Count.ToString() : string.Empty));

For:

var str = "aaabbccdddeezbbb";

the result is:

a3b2c2d3e2zb3

  • First get letter groups with regex and their legths
  • Then aggregate them to the final string
t3chb0t
  • 44.7k
  • 9
  • 84
  • 191