K-Dominant Character

You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.

You have to find minimum k such that there exists at least one k-dominant character.

Input
The first line contains string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 100000).

Output
Print one number — the minimum value of k such that there exists at least one k-dominant character.

Examples
Input
abacaba
Output
2
Input
zzzzz
Output
1
Input
abcde
Output
3

题意:
求一个字符串中任意长度为k的子串中存在同一个字母,求最小的k;
思路:
长度为k的子串存在相同的字母,假设字母存在字母a,则相邻的两个字母a的下标的差都小于等于k(包括第一个a到串首的距离和最后一个a到串尾的距离)
则最小的k是所有字母最大的差的最小值!!!

#include<bits/stdc++.h>
using namespace std;

int main()
{
	string s;
	cin>>s;
	int len=s.size();
	int num[100],last[100],mp[100];//num[i-'a'] 字母i的最大差值 last[i-'a'] 上一个字母 i 的下标
	memset(num,-1,sizeof num);
	memset(last,-1,sizeof last);//初始化为-1
	for(int i=0;i<len;i++)
	{
		num[s[i]-'a']=max(num[s[i]-'a'],i-last[s[i]-'a']);
		last[s[i]-'a']=i;//更新下标
	}
	int ans=0x3f3f3f3f;
	for(int i=0;i<26;i++)//最小的那个值即为答案
		{
			num[i]=max(num[i],len-last[i]);
			ans=min(num[i],ans);
		}
	cout<<ans;
	return 0;
 } 
原文地址:https://www.cnblogs.com/neflibata/p/12871812.html