1. 程式人生 > >51Nod - 1127 最短的包含字符串

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

main using show bbb ble sizeof output ons ace

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\n");
		}else{
			printf("%d\n", ans ); 
		}
	}
	return 0; 
}

  

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