Minimum Window Substring -- LeetCode

题目:

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).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思路:使用两个指针,一个hash表,两个指针为了记录宽度,hash表为了记录是否存在,目标字符在两个指针之间出现了多少次,直到所有字符都出现在了这段子串内,移动前面的指针,直到某一个字符出现在子串中一次,那么这个空间的长度就是当前最短的,这样遍历直到把所有字符串遍历结束

#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
一个字符串能包含另一个字符串中所有字母的子串的最小长度 
*/ 

string MinLength(string& src,string& dest)
{
	int i=0,j=0;
	int flag =0;
	int len=src.size();
	int pos=0;
	vector<int> hash(26,-1);
	for(i=0;i<dest.length();i++)
		hash[dest[i]-'A'] =0;
//	for(i=0;i<hash.size();i++)
//		cout<<hash[i]<<endl;
	for(i=0;i<src.size();i++)
	{
		if(hash[src[i]-'A'] >=0)
		{
			hash[src[i]-'A']++;
			if(hash[src[i]-'A'] ==1)
				flag++;
		
		}
		if(flag == dest.length())
		{
			//cout<<"=="<<endl;
	//		cout<<"j is "<<j<<" i is "<<i<<endl;	
			for(;j<i;j++)
			{
				if(hash[src[j]-'A'] == 1)
					break;
				else
					hash[src[j]-'A']--;
					
			}
			if(len >i-j+1)
			{
				len = i-j+1;
				pos =j;						
			}
				
			hash[src[j]-'A'] = 0;
			j++;
			flag--;
		}
	}
	cout<<string(src,pos,pos+len)<<" pos is "<<pos<<" len is "<<len<<endl;;
	return string(src,pos,pos+len);
} 

int main()
{
	string src("ADOBECODEBANCAAABC");
	string dest("ABC");
	cout<<MinLength(src,dest);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值