Print the digram which appears maximum number of times in a string
A digram is a sequence of 2 consecutive characters
I/o - "asddaaasadedadaddasasasasas"
O/P - "as"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
    static void Main()
    {
        string input = "asddaaasadedadaddasasasasas";
        Dictionary<string, int> digramCount = new Dictionary<string, int>();
        // Count all digrams in the string
        for (int i = 0; i < input.Length - 1; i++)
        {
            string digram = input.Substring(i, 2);
            if (digramCount.ContainsKey(digram))
                digramCount[digram]++;
            else
                digramCount[digram] = 1;
        }
        // Find the digram with maximum occurrences
        var maxDigram = digramCount.OrderByDescending(x => x.Value).First();
        Console.WriteLine($"\"{maxDigram.Key}\" appears {maxDigram.Value} times");
    }
}
 
 
No comments:
Post a Comment