Max count of consecutive occurrence of characters in a string

Given a string, print the maximum count of consecutive occurrence of characters within it. For example given an input string say “aaabbcccddddaa”, the output should be 4.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string testString = "aaabbcccddddaa";
            string newString = "";
            int count = 0;
            int maxCount = 0;
            for (int i = 0; i < testString.Length; i++)
            {
                if (i < testString.Length - 1)
                {
                    if (testString[i] == testString[i + 1])
                    {
                        count++;
                    }
                    else
                    {
                        count++;
                        newString = newString + testString[i] + count;
                        if (maxCount < count)
                        {
                            maxCount = count;
                        }
                        count = 0;
                    }
                }
                else
                {
                    count++;
                    newString = newString + testString[i] + count;
                    if (maxCount < count)
                    {
                        maxCount = count;
                    }
                }
            }
            Console.WriteLine("Original String = " + testString);
            Console.WriteLine("Modified String = " + newString);
            Console.WriteLine("Max count of consecutive occurrence of characters = " + maxCount);
        }
    }
}
Output:
=========
Original String = aaabbcccddddaa
Modified String = a3b2c3d4a2
Max count of consecutive occurrence of characters = 4
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s