Sunday, July 28, 2013

Find the smallest window in a string containing all characters of another string


Given two strings string1 and string2, find the smallest substring in string1 containing all characters of string2 efficiently.




#include<iostream>
using namespace std;
int main()
{
    string source;
    string target;
    cin>>source;
    cin>>target;
    
    int hasFound[255] = {0};
    int needToFind[255] = {0};
    
    for(int i = 0; i < source.size(); i++)
    {
        needToFind[source[i]]++;
    }
    
    
    
    int si =0;
    int ti = 0;
    int cnt  =0;
    string answer = "";
    while(ti < target.size())
    {
        hasFound[target[ti]]++;
        if(hasFound[target[ti]] <= needToFind[target[ti]])
        {
            cnt++;
        }
        
        
        if(cnt >= source.size())
        {
            // there is a substring from si to ti which
            // has data same as source 
            // but might be greater than  source
            // start moving source
            while(needToFind[target[si]] == 0)
            {
                si++;
            }
            
            while(hasFound[si] >  needToFind[si])
            {
                si++;
                hasFound[si]--;
            }
            
            string result = target.substr(si, ti - si +1 );  
            if(answer == "" || result.size() < answer.size())
            {
                answer = result;
            }
                
        }
        
        ti++;
    }
    
    
    cout<<answer;
    return 0;
    

}

No comments:

Post a Comment