Sunday, July 22, 2012

Printing the max length substring with max repetition count


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = Console.ReadLine();
int[] maxcount = new int[str.Length + 1];
string[] maxstring = new string[str.Length + 1];
for (int i = 0; i < str.Length; i++)//Starting point of the substring to be searched.
{
for (int length = 1; length <= str.Length - i; length++)//Length of the substring to be searched.
{
int count = 0;
string substr1 = str.Substring(i, length);
for (int j = 0; j <= str.Length - length; j++)//Starting point in the string from where the search starts.
{
string substr2 = str.Substring(j, length);
if (substr1 == substr2)
{
count++;
}
}
if (maxcount[length] < count)
{
maxcount[length] = count;
maxstring[length] = substr1;
}
}
}
int maxcnt = 0;
string maxstr="";
for (int i = 1; i <= str.Length; i++)
{
if (maxcnt <= maxcount[i])
{
maxcnt = maxcount[i];
maxstr = maxstring[i];
}
}
Console.WriteLine(maxstr + " has the max length: " + maxcnt);
}
}
}
abcabcabcabc
abc has the max length: 4
Press any key to continue . . .

No comments:

Post a Comment