51Nod

51Nod - 1127 最短的包含字符串

给出一个字符串,求该字符串的一个子串S,S包含A-Z中的全部字母,并且S是所有符合条件的子串中最短的,输出S的长度。如果给出的字符串中并不包括A-Z中的全部字母,则输出No Solution。
 
Input
第1行,1个字符串。字符串的长度 <= 100000。
Output
输出包含A-Z的最短子串长度。如果没有符合条件的子串,则输出No Solution。
Input示例
BVCABCDEFFGHIJKLMMNOPQRSTUVWXZYZZ
Output示例
28

题解: 

   双指针 + 计数数组,可以在 O(n ) 时间内解决。 

#include <iostream> 
#include <cstdio> 
#include <cstdlib> 
#include <cstring> 
using namespace std;
const int MAXN = 100000 + 5; 

int vis[26]; 
char ch[MAXN]; 

int main(){
	freopen("in.txt", "r", stdin); 

	int len, cnt, i, j, ans;  
	while(scanf("%s", ch) != EOF){
		getchar(); 
		len = strlen(ch); 
		memset(vis, 0, sizeof(vis)); 
		i = 0; j = 0;  ans = len + 1;  cnt = 0; 
		while(j < len){
			if(vis[ch[j] - 'A'] == 0){ 
				cnt += 1; 
			}
			vis[ch[j] - 'A'] += 1; 
			j++; 
			if(cnt == 26){ 
				while( i<j && vis[ch[i] - 'A'] > 1){
					vis[ch[i] - 'A'] -= 1; 
					i++; 
				} 
				if( ans > (j - i) ){
					ans = j - i; 
				} 
			}
		} 
		if(ans == len + 1){
			printf("No Solution
");
		}else{
			printf("%d
", ans ); 
		}
	}
	return 0; 
}

  

原文地址:https://www.cnblogs.com/zhang-yd/p/6842895.html