Interview Question Categories

FIND FIRST REPEATED STRING WITH 3 CHARS

FIND FIRST REPEATED STRING WITH 3 CHARS


namespace FirstRepeatedStringWithMin3Chars
{
    //Given a String "abcxrrxabcrr"
    //Find the first repeated string with minimum 3 character ?
    //Answer is "abc" min 3 characters.
    class Program
    {
        //Here HashSet is being used, we can also do it using Tries.
        public static String FindRepeatedString(String Str)
        {
            HashSet<String> Set = new HashSet<string>();

            int index = 0;
            String SubString = null;

            while (index + 3 < Str.Length)
            {
                SubString = Str.Substring(index, 3);
                if(Set.Contains(SubString))
                {
                    return SubString;
                }
                Set.Add(SubString);
                index++;
            }
            return null;
        }

        static void Main(string[] args)
        {
            String Str = "aaaagfyeueyhgfkeury";

            Console.WriteLine(FindRepeatedString(Str));
        }
    }
}

No comments:

Post a Comment