How to find smallest substring which contains all characters from a given string?

后端 未结 15 1126
灰色年华
灰色年华 2020-12-02 07:36

I have recently come across an interesting question on strings. Suppose you are given following:

Input string1: \"this is a test string\"
Input strin         


        
15条回答
  •  佛祖请我去吃肉
    2020-12-02 08:25

    C# Implementation:

    public static Tuple FindMinSubstringWindow(string input, string pattern)
    {
        Tuple windowCoords = new Tuple(0, input.Length - 1);
        int[] patternHist = new int[256];
        for (int i = 0; i < pattern.Length; i++)
        {
            patternHist[pattern[i]]++;
        }
        int[] inputHist = new int[256];
        int minWindowLength = int.MaxValue;
        int count = 0;
        for (int begin = 0, end = 0; end < input.Length; end++)
        {
            // Skip what's not in pattern.
            if (patternHist[input[end]] == 0)
            {
                continue;
            }
            inputHist[input[end]]++;
            // Count letters that are in pattern.
            if (inputHist[input[end]] <= patternHist[input[end]])
            {
                count++;
            }
            // Window found.
            if (count == pattern.Length)
            {
                // Remove extra instances of letters from pattern
                // or just letters that aren't part of the pattern
                // from the beginning.
                while (patternHist[input[begin]] == 0 ||
                       inputHist[input[begin]] > patternHist[input[begin]])
                {
                    if (inputHist[input[begin]] > patternHist[input[begin]])
                    {
                        inputHist[input[begin]]--;
                    }
                    begin++;
                }
                // Current window found.
                int windowLength = end - begin + 1;
                if (windowLength < minWindowLength)
                {
                    windowCoords = new Tuple(begin, end);
                    minWindowLength = windowLength;
                }
            }
        }
        if (count == pattern.Length)
        {
            return windowCoords;
        }
        return null;
    }
    

提交回复
热议问题