想成为Google工程师?先回答这15个面试问题【这只是一必要条件】(六)

    7. 给你一个字符串,找出包含给定字符集的最小窗口

   找到最小的窗口,首先这个窗口只有长度,没有宽度。因此我们可以假设两个滑块a, b;起初先让a,b都在文本的开头,为了记录区域内文本出现的字符的个数,我们声明一个数组arr。先让b从文本头往后滑动,如果字符在选定字符内部,则在arr相应的位置+1,直到第一次找到一块区域包含了所有的字符,即arr中每个元素都大于0。此时,滑动a,直到第一次区域不包括所有的字符,即arr内部有个元素==0。此时b-a+1的宽度就是包含给定字符集的一个窗口。如上再次滑动b,a,可以找到所有条件的最小窗口大小。

   

     时间复杂度,循环滑动b到文件末尾,内部滑动a,相当于两次遍历,所以时间复杂度为O(n)。代码如下:

#include<iostream>
#include <fstream>
#include <string>

using namespace std;

#define  LARGER 0X7FFFFFFF

ifstream fin("input.txt");
ofstream fout("output.txt");

string text;
struct Window
{
	int s;
	int e;
};

const int SIZE = 100;
char arr[SIZE];
int number[SIZE] = {0};
int n;
int flag = 0;
Window w;
int result = LARGER;
Window rw;

//读取数据
void read()
{
	getline(fin, text);

	fin >> n;
	for (int i=0; i < n; i ++)
	{
		fin >> arr[i];
	}
}

//获取字符在指定字符中的坐标
int getIndex(char c)
{
	for (int i=0; i < n; i++)
	{
		if (arr[i] == c)
		{
			return i;
		}
	}
	return -1;
}

void getwindow()
{
	w.s = 0;
	for (w.e = 0; w.e < text.size(); w.e ++)
	{
		int index = getIndex(text[w.e]);
		if (index != -1)
		{
			if (number[index] == 0)
			{
				flag ++;
			}
			number[index] ++;
		}//end if index == -1
		
		//include all character
		if (flag == n)
		{
			for (; w.s <= w.e; w.s ++ )
			{
				int index = getIndex(text[w.s]);

				if (index != -1)
				{
					number[index] --;

					if (number[index] <= 0)
					{
						flag --;
						if(w.e - w.s + 1 < result)
						{
							result = w.e - w.s + 1;
							rw.s = w.s;
							rw.e = w.e;
						}//end if
						break;
					}//end number[index]
				}//end if index
			}//end for w.s
		}//end flag == n
	}//end for w.e
}

void print()
{
	for (;rw.s <= rw.e; rw.s ++)
	{
		fout << text[rw.s];
	}
	fout <<endl;
}

int main()
{
	read();
	getwindow();
	print();
	return 0;
}

数据如下:

It is hard to find someone that does not have a protective outer layer, a wall of facts and knowledge and internet presence and book smarts that seem to show off who they are. We all tend to display something to the world that shows who we “are” yet how many people actually get beyond that outer skin and know the real us. Its fine to present ourselves to the world, indeed we cannot get to know more than maybe 5-15 people in depth. But are we even retaining that in this new fast paced world? I ask in order to spark an interest in you to really get to know some people, really delve into who they are, and maybe even walk the line to share something deep about yourself. We all have hopes and fears, why not realize we share the same things and lean on each other?
5
abcde


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值