Skip to content

Instantly share code, notes, and snippets.

@WennderSantos
Created November 1, 2018 20:57
Show Gist options
  • Save WennderSantos/73ac7931b7f8392fcd678af85a150ebb to your computer and use it in GitHub Desktop.
Save WennderSantos/73ac7931b7f8392fcd678af85a150ebb to your computer and use it in GitHub Desktop.
RunLength. O(n)
static void Main(string[] args)
{
var input = "wwwwaaadexxxxxxywww";
Console.WriteLine(input);
for (var i = 0; i < input.Length - 1; i++)
{
var count = 1;
while(i < input.Length - 1
&& input[i] == input[i + 1])
{
count++;
i++;
}
Console.Write($"{count}{input[i]} "); //4w 3a 1d 1e 6x 1y 3w
}
}
@WennderSantos
Copy link
Author

           var input = "bbooppqqtghnvvvoopgggggggggggl";
            var result = new StringBuilder();
            var count = 1;

            for (var i = 0; i < input.Length; i++)
            {
                if (i == input.Length - 1)
                {
                    result.Append(input[i]);
                    result.Append(count);
                    break;
                }

                if (input[i + 1] == input[i])
                    count++;
                else
                {
                    result.Append(input[i]);
                    result.Append(count);
                    count = 1;
                }

            }

            Console.WriteLine(result.ToString().Length > input.Length ? input : result.ToString());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment