【leetcode】Minimum Window Substring

  • 设置两个指针begin和end,表示一个窗口
  • 移动end直到找到一个有效的窗口
  • 移动begin找到长度更小的有效窗口
class Solution {
public:
    string minWindow(string s, string t)
    {
        vector<int> dict(128, 0);
        for (auto c : t)
            ++dict[c];
        int counter = t.size();
        int begin = 0;
        int end = 0;
        int head = 0;
        int minlen = INT_MAX;
        while (end < s.size())
        {
            if (dict[s[end++]]-- > 0)
                --counter;
            while (counter == 0)
            {
                if (end - begin < minlen)
                {
                    minlen = end - begin;
                    head = begin;
                }
                if (dict[s[begin++]]++ == 0)
                    ++counter;
            }
        }
        return minlen == INT_MAX ? "" : s.substr(head, minlen);
    }
};

Reference: https://leetcode.com/discuss/72701/here-10-line-template-that-can-solve-most-substring-problems

点赞