76. Minimum Window Substring
典型Sliding Window的问题,维护一个区间,当区间满足要求则进行比较选择较小的字串,重新修改start位置。
思路虽然不难,但是如何判断当前区间是否包含所有t中的字符是一个难点(t中字符有重复)。可以通过一个hashtable,记录每个字符需要的数量,这个数量可以为负(当区间内字符数超过所需的数量)。还需要一个count判断多少字符满足要求了,如果等于t.size(),说明当前窗口的字串包含t里所有的字符了。
class Solution { public:string minWindow(string s, string t) {unordered_map<char,int> hash; // char and the num it needs (it can be minus)int start=0;string res; int min_len=INT_MAX;for (char ch:t) hash[ch]++; int count=0;for (int end=0;end<s.size();++end){if (hash.count(s[end])){--hash[s[end]];if (hash[s[end]]>=0) ++count;while (count==t.size()){if (end-start+1<min_len){min_len = end-start+1;res = s.substr(start,end-start+1);}if (hash.count(s[start])){++hash[s[start]];if (hash[s[start]]>0) --count;}++start;}}}return res;} };
567. Permutation in String
和上面一题几乎一模一样,但是全排列的话,不能有其他的字母。这也很好解决,如果count==s1.size(),且字符串长度和s1.size()相等的话,就一定是s1的一个排列。
其实这道题和上一道题,都不用加 hash.count 判断当前字符在不在s1中,因为不在s1中的字符出现后,hash[ch]一定<0;从窗口移除后hash[ch]也不会超过0,因此对count没有影响。
这道题也和 438. Find All Anagrams in a String 很像,由于需要找的字符串长度是固定的,也可以固定长度,滑动窗口来做。
class Solution { public:bool checkInclusion(string s1, string a) {unordered_map<char,int> hash;for (char ch:s1) ++hash[ch];int count=0;int start=0;for (int end=0;end<a.size();++end){if (hash.count(a[end])){ //this char is in s1--hash[a[end]];if (hash[a[end]]>=0) ++count;while (count==s1.size()){if (end-start+1==s1.size()) return true;if (hash.count(a[start])){++hash[a[start]];if (hash[a[start]]>0) --count;}++start;}}}return false;} };