Interview Question Categories

CHARACTER COUNTING

CHARACTER COUNTING


/* Count the adjacent characters in the given string
 * and print in the following fashion : count1{char1}count2{char2}....
 * Example if given string is str = "AAABBGFF" then 
 * output is "3{A}2{B}1{G}2{F}"
*/ 

namespace CharacterCountingProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            String pattern = "AAABBGFF";
            char prev = pattern[0];
            int count = 1;

            for (int i = 1; i < pattern.Length; i++)
            {
                if (pattern[i] == prev) count++;
                else
                {
                    Console.Write(count + "{" + prev + "}");
                    prev = pattern[i];
                    count = 1;
                }
            }
            Console.Write(count + "{" + prev + "}");
        }
    }
}

No comments:

Post a Comment