Wednesday, June 12, 2013

Given a string, return start position of largest repeated characters (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
   String string1 = "aaaaabbbbbbbbbbbbbbefxsscc";
  //String string2 = "aaaaaa";
        int pos = findStartPos(string1);
        Console.WriteLine(pos.ToString());
        Console.ReadKey();
        }
   

        public static int findStartPos(string str)
        {
            //this is the start position of the concurrent longest string
            int start = 0;
            //if another longer string is encountered, this becomes the start of the longer concurrent string
            int newStart = 0;
            //count of chars in the string
            int count = 1;
            //maximum length of the substring of con current chras
            int maxCount = 1;
            if (str.Length > 0)
            {
                char[] strArr = str.ToCharArray();
                for (int i = 1; i < strArr.Length; i++)
                {
                    if (strArr[i] == strArr[i - 1])
                    {
                        count++;
                        if (count > maxCount)
                        {
                            start = newStart;
                            maxCount = count;
                        }
                       
                    }
                    else
                    {
                        newStart = i;
                        count = 1;
                    }
                }
            }
            return start;
        }

 }
}

No comments: