Leetcode 76 Solution

This article provides solution to leetcode question 76 (minimum-window-substring)

https://leetcode.com/problems/minimum-window-substring

Solution

class Solution {
public:
    string minWindow(string s, string t) {
        if (t.size() == 0)
            return "";

        int l = 0;
        int r = 0;
        int min_val = INT_MAX;
        int min_l = -1;
        int min_r = -1;
        int expectCount[256] = {0};
        int appearCount[256] = {0};

        unordered_set<unsigned char> unmet_chars;

        for (int i = 0; i < t.size(); i++)
        {
            unsigned char ch = (unsigned char)t[i];
            unmet_chars.insert(ch);
            expectCount[ch]++;
        }

        while (r < s.size())
        {
            unsigned char ch = (unsigned char)s[r];
            appearCount[ch]++;

            if (appearCount[ch] >= expectCount[ch])
                unmet_chars.erase(ch);

            unsigned char left_ch = (unsigned char)s[l];

            while (appearCount[left_ch] > expectCount[left_ch] && l < r)
            {
                appearCount[left_ch]--;
                left_ch = (unsigned char)s[++l];
            }

            if (unmet_chars.empty() && min_val > r - l + 1)
            {
                min_l = l;
                min_r = r;
                min_val = r - l + 1;
            }

            r++;
        }

        return min_l == -1 ? "" : s.substr(min_l, min_r - min_l + 1);
    }
};