首页 > Windows开发 > 详细

Minimum Window Substring -- LeetCode

时间:2015-04-01 09:33:24      阅读:241      评论:0      收藏:0      [点我收藏+]

题目:

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;
}


Minimum Window Substring -- LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/44801645

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!