数据结构——滑动窗口Leetcode209,438,76

滑动窗口

209
给定一个sum,求和大于等于sum的最短子串,返回最短子串的长度
      滑动窗口一定是r++,l++,对撞指针是r--,l++       
class Solution {
public:
	int minSubArrayLen(int s, vector<int>& nums) {
		//判断特殊情况

		int l = 0;
		int r = -1;
		int sum = 0;
		int res = nums.size() + 1;

		while (l < nums.size())
		{
			if (r + 1 < nums.size() && sum < s)
				sum += nums[++r];
			else
				sum -= nums[l++];

			if (sum >= s)
				res = min(res,r-l+1);
		}

		if (res == nums.size() + 1)
			return 0;
		return res;
	}
};

438

class Solution {
public:
	vector<int> findAnagrams(string s, string p) {
		if (s.empty())
			return{};

		vector<int> res;
		vector<int> hash1(256,0), hash2(256,0);  //用两个hash表来记录滑动窗口和p中出现的字符及其出现的次数,都初始化为0
		                                         //hash1是指p的hash表
                                                 //hash2是指滑动窗口的hash表
		for (int i = 0; i < p.length(); i++)
		{
			hash1[p[i]]++;
			hash2[s[i]]++;
		}

		if (hash1 == hash2) res.push_back(0);

		//这个滑动窗口每次向前滑动一格
		//尝试改进,如果遇到p中没有的直接跳到,该字符的下一个字符
		for(int i=p.length();i<s.length();i++)
		{
			hash2[s[i]]++;
		    hash2[s[i - p.length()]]--;
			if (hash1 == hash2)
				res.push_back(i- p.length() + 1);
		}
		return res;
	}
};

76
class Solution {
public:
	string minWindow(string s, string t) {
		//用一个hash表来记录t中的字符
		unordered_map<char, int> t_map;

		for (auto ch : t) t_map[ch]++;
		
		int min_len = s.size() + 1, min_begin = 0;
		int count = 0;
		int l = 0,r = 0;
		for(;r<s.size();r++)
		{
			if (t_map.find(s[r]) != t_map.end())//有T中的字符
			{
				t_map[s[r]]--;
				if (t_map[s[r]] >= 0)
					count++;

				while (count == t.size())
					//当t_map中的所有频率都为0时,已经找到了包含t的子串
				{
					if (r - l + 1 < min_len)
					{
						min_len = r - l + 1;
						min_begin = l;
					}
					if (t_map.find(s[l])!= t_map.end())
						if((++t_map[s[l]])> 0)
						   count--;
					++l;
				}		
			}	
		}
		cout << min_len << endl;
		if (min_len>s.size())
			return "";
		return s.substr(min_begin, min_len);
	}
};

猜你喜欢

转载自blog.csdn.net/eereere/article/details/80156810