DEV Community

Ankur Soni
Ankur Soni

Posted on

find the shortest substring in a string c#

static void Main(string[] args)
        {
            Program program = new Program();
            int totalStudent = 3;
            int totalSubject = 5;
            int[,] marks = {{75,76,65,87,87},
                            {78,76,68,56,89},
                            {67,87,78,77,65}};

            string firstString = "this is a test string";
            string secondString = "tist";

            program.Shortest(firstString, secondString);

        }

        public void Shortest(string input1, string input2)
        {
            int minLength = input1.Length;
            string smallestSubstring = string.Empty;

            for (int i = 0; i < input1.Length; i++)
            {
                for(int j = i; j < input1.Length; j++)
                {
                    string substr = input1.Substring(i, j - i + 1);
                    if (ContainsAllCharacters(substr, input2))
                    {
                        int currentLength = substr.Length;
                        if (currentLength < minLength)
                        {
                            minLength = currentLength;
                            smallestSubstring = substr;
                        }
                    }
                }
            }
            Console.WriteLine(smallestSubstring);

        }

        private bool ContainsAllCharacters(string input1, string input2) 
        {
            int[] count = new int[256];

            foreach (char ch in input2)
                count[ch]++;

            foreach (char ch in input1)
            {
                if (count[ch] > 0)
                    count[ch]--;
            }

            foreach (int val in count)
            {
                if (val > 0)
                    return false;
            }

            return true;
        }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)