【LeetCode76.最小覆盖子串】

题目连接

76. 最小覆盖子串 - 力扣(LeetCode)

思路

  1. 先统计t串中的字符的个数;
  2. 设置两个索引i和j。固定j时,i遍历到至少涵盖子串t的位置的下一位,接着,由于j~k的字符可能是不必要的(对应cnt[s[j]] < 0),因此j可以移到k+1的位置。

代码实现

class Solution {
public:
    string minWindow(string s, string t) {
        int m = s.size();
        int n = t.size();
        unordered_map cnt;
        int need = n;
        for (char ch : t) {
            cnt[ch]++;
        }
        int i = 0, j = 0;
        int start = -1, len = m + 1;
        while (i < m && j < m) {
            // i-1遍历的位置是当前满足条件的最小右边界位置
            while (need > 0 && i < m) {
                if (cnt[s[i]] > 0) need--;
                cnt[s[i]]--;
                i++;
            }
            // j遍历的位置是当前满足条件的左边界最小位置
            while (j < m && cnt[s[j]] < 0) {
                cnt[s[j]]++;
                j++;
            }
            if (need == 0) {
                if (len > i - j) {
                    len = i - j;
                    start = j;
                }
            }
            need++;
            cnt[s[j]]++;
            j++;
        }
        return len == m + 1 ? "" : s.substr(start, len);
    }
};

你可能感兴趣的:(【LeetCode76.最小覆盖子串】)