给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC" 输出: "BANC"
说明:
- 如果 S 中不存这样的子串,则返回空字符串
""
。 - 如果 S 中存在这样的子串,我们保证它是唯一的答案。
解答:本题参考了博客:http://www.cnblogs.com/grandyang/p/4340948.html。本题使用滑动窗口法来求解。设置的非常精妙,主要在两点:右侧窗口向右滑动和左侧窗口向右滑动。
具体解题逻辑如下:
【1】利用非排序哈希表用来存储最小字串中的字符,记为 letterCnt。
【2】遍历S,若S中字符串在letterCnt中,那么letterCnt[ s[i] ]--。如果letterCnt[ s[i] ] > 0, 说明s中未有足够的 T中 s[i]字符,需要循环查找;
【3】若cnt 等于 T的字符个数,说明子字符串已经找到,利用求最小长度和最小字符串;
【4】若右侧有字子服中的字符,那么标记该字符串并且继续查找;
【5】左侧窗口不断向右滑动
//76 string minWindow(string s, string t) { string res{""}; unordered_map<char,int> letterCnt; int left=0, cnt =0, len=INT_MAX; for(char c: t) letterCnt[c]++; for(int i=0;i<s.size();i++) { if(--letterCnt[s[i]]>=0) cnt++; while(cnt==t.size()) { if(len > i-left+1) { len = i - left +1; res = s.substr(left, len); } if(++letterCnt[s[left]] > 0) cnt--; left++; } } return res; }//76