Friendship of Frog
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1463 Accepted Submission(s): 960
The closest friends are a pair of friends with the minimum distance. Help us find that distance.
Every test case only contains a string with length N, and the ith character of the string indicates the country of ith frogs.
⋅ 1≤T≤50.
⋅ for 80% data, 1≤N≤100.
⋅ for 100% data, 1≤N≤1000.
⋅ the string only contains lowercase letters.
題意:給一個長度不超過1000的字符串,求相同字符最小間隔,沒有相同字符輸出-1
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define ll __int64
using namespace std;
char s[2000];
int main()
{
int T;
scanf("%d",&T);
int ca=1;
while(T--)
{
scanf("%s",s);
int len=strlen(s);
int ans=999999;
int flag;
for(int i=0;i<26;i++)
{
int f='a'+i;
flag=0;
int pos;
int dis=999999;
for(int j=0;j<len;j++)
{
if(f==s[j])
{
if(flag==0)//記錄該字符第一次出現的位置
{
pos=j;
flag=1;
continue;
}
dis=min(dis,j-pos);
pos=j;
}
}
ans=min(dis,ans);
}
if(ans==999999)
ans=-1;
printf("Case #%d: %d\n",ca++,ans);
}
return 0;
}