Minimum Window Substring

for code2:判断条件写在while外面,确保j==m的时候(最后一击)也会被考虑;

code

class Solution {
public:    
    /**
     * @param source: A string
     * @param target: A string
     * @return: A string denote the minimum window
     *          Return "" if there is no such a string
     */
    string minWindow(string &source, string &target) {
        // write your code here
        if(source.size() == 0 || target.size() == 0)
        {
            return "";
        }

        map<char, int> hash;

        for(char c : target)
        {
            hash[c]++;
        }

        int i = 0;
        int j = 0;
        string ans;
        int ret = INT_MAX;
        int count = hash.size();

        for(; i<source.length(); i++)
        {
            while(j < source.length())
            {
                if(count != 0)
                {
                    char cur = source[j];
                    hash[cur]--;
                    if(hash[cur] == 0)
                    {
                        count--;
                    }
                    j++;
                }
                else
                {
                    break;
                }
            }

            if(count == 0 && j-i < ret)
            {
                ret = j - i;
                ans = source.substr(i, j-i);
            }

            char tmp = source[i];
            if(hash[tmp] == 0)
            {
                count++;
            }
            hash[tmp]++;
        }

        return ans;

    }
};

code2


class Solution {
public:
    string minWindow(string s, string t) {
        if(t.empty() || s.empty() || t.length() > s.length())
        {
            return "";
        }

        int n = s.length();
        int j = 0;

        map<char, int> hash;
        for(int i = 0; i<t.length(); i++)
        {
            hash[t[i]]++;
        }

        int cur = hash.size();
        int min_length = INT_MAX;
        string ret_string = "";

        for(int i = 0; i<n; i++)
        {
            while(j < n)
            {
                if(cur == 0)
                {
                    break;
                }
                else
                {
                    char c = s[j];
                    hash[c]--;
                    if(hash[c] == 0)
                    {
                        cur--;
                    }
                    j++;
                }
            }

            if(cur == 0 && j-i < min_length)
            {
                min_length = j-i;
                ret_string = s.substr(i, j-i);
            }

            hash[s[i]]++;
            if(hash[s[i]] == 1)
            {
                cur++;
            }

        }

        return ret_string;
    }
};

results matching ""

    No results matching ""