Algorithm to find the minimum length of substring having all characters of other string

前端 未结 4 925
我寻月下人不归
我寻月下人不归 2021-02-04 18:15

I have a two strings:
string1 - hello how are you,
String2 - olo (including space character)

Output: lo ho ( hello

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 19:08

    There is this algorithm which does this in O(N).

    Idea: Have 2 arrays, viz. isRequired[256] and isFound[256] which tells the frequency of each character in S and while parsing the string S, the frequency of each character that has found yet. Also, keep a counter which tells when a valid window is found. Once a valid window is found, we can shift the window (towards right) maintaining the given invariant of the question.

    Program in C++:

    void findMinWindow(const char *text, const char *pattern, int &start, int &end){
            //Calcuate lengths of text and pattern
            int textLen = strlen(text);
            int patternLen = strlen(pattern);
    
            // Declare 2 arrays which keep tab of required & found frequency of each char in pattern
            int isRequired[256] ; //Assuming the character set is in ASCII
            int isFound[256];
            int count = 0; //For ascertaining whether a valid window is found
    
            // Keep a tab of minimum window 
            int minimumWindow = INT_MAX;
    
            //Prepare the isRequired[] array by parsing the pattern
            for(int i=0;i isRequired[s[i]]){
                       //Either of the above 2 conditions means we should increment i; however we 
                       // must decrease isFound for this char as well.
                       //Hence do a check again
                       if(isFound[s[i]] > isRequired[s[i]]){
                          isFound[s[i]]--;
                       }
                       i++;
                  }
    
                   // Note that after the while loop, the invariant is still maintained
                   // Lets check if we did better
                   int winLength = j-i+1;
                   if(winLength < minimumWindow){
                      //update the references we got
                      begin = i;
                      end = j;
                      //Update new minimum window lenght
                      minimumWindow = winLength;
                   }
              } //End of if(count == patternLen)
         } //End of for loop 
    }
    

提交回复
热议问题