最小覆盖字串

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

eg,
S = “ADOBECODEBANC”
T = “ABC”

Minimum window is “BANC”.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_OUT_LEN 256

int min_window(char *str, char *dest, int &min_begin, int &min_end)
{
	char need_to_find[256] = {0};
	char has_found[256] = {0};
	int begin = 0, end = 0;
	int count = 0;
	int str_len = 0, dest_len = 0;
	int i = 0;
	int min_window_len = MAX_OUT_LEN;

	if(str == NULL || dest == NULL)
	{
		printf("input wrong!\n");
		return -1;
	}

	str_len = strlen(str);
	dest_len = strlen(dest);

	for(i = 0; i < dest_len; i++)
	{
		need_to_find[dest[i]]++;
	}

	for(begin = 0, end = 0; end < str_len; end++)
	{
		if(need_to_find[str[end]] == 0)
		{
			continue;
		}

		has_found[str[end]]++;
		if(has_found[str[end]] <= need_to_find[str[end]])
		{
			count++;
		}

		if(count == dest_len)
		{
			int get_len = 0;
			while(need_to_find[str[begin]] == 0 || has_found[str[begin]] > need_to_find[str[begin]])
			{
				if(has_found[str[begin]] > need_to_find[str[begin]])
				{
					has_found[str[begin]]--;
				}
				begin++;
			}
			get_len = end - begin + 1;
			if(get_len < min_window_len)
			{
				min_begin = begin;
				min_end = end;
				min_window_len = get_len;
			}
		}
	}

	return count == dest_len ? 0 : -1;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值