1. 程式人生 > >資料結構——滑動視窗Leetcode209,438,76

資料結構——滑動視窗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);
	}
};