76. Minimum Window Substring

本文深入探讨了如何在给定字符串S中找到包含另一字符串T所有字符的最小窗口子串,采用哈希表和双指针技术实现复杂度为O(n)的高效算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

最小窗口子串,已知字符串S和字符串T,求在S中的最小窗口(区间),使得这个区间中包含字符串T中的所有字符。

解法:采用哈希表记录出现的字符,用双指针界定窗口,寻找包含字符串T中的所有字符的最小窗口。

class Solution {
private:
bool isContain(vector<int> map_cur_s, vector<int> map_t)
{
	int len = map_cur_s.size();
	for (int i = 0; i < len; i++)
	{
		if (map_cur_s[i] < map_t[i])
			return false;
	}
	return true;
}
public:
   string minWindow(string s, string t) {
	if (s.size() < t.size())
		return "";
		
	vector<int> map_t(128,0);
	set<char> log_t;
	for (int i = 0; i < t.size(); i++)
	{
		map_t[t[i]]++;
		log_t.insert(t[i]);
	}
	int begin = 0, i = 0;
	string result;
	int minLen = INT_MAX;
	vector<int> map_cur_s(128, 0);
	while (i <= s.size())
	{
		map_cur_s[s[i]]++;	
		while (begin <= i)
		{
			if (log_t.find(s[begin]) == log_t.end() || map_cur_s[s[begin]] > map_t[s[begin]])
			{
				map_cur_s[s[begin]]--;
				begin++;
			}
			else
			{
				break;
			}
		}

		int count = i - begin + 1;
		if (isContain(map_cur_s, map_t))
		{
			if (count < minLen)
			{
				minLen = count;
				result = s.substr(begin, count);
			}			
		}		
		i++;		
	}
	return result;
}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值