Friendship of Frog
Problem Description
N frogs from different countries are standing in a line. Each country is represented by a lowercase letter. The distance between adjacent frogs (e.g. the
1st and the
2nd frog, the
N−1th and the
Nth frog, etc) are exactly
1 . Two frogs are friends if they come from the same country.
The closest friends are a pair of friends with the
minimum distance. Help us find that distance.
Input
First line contains an integer
T , which indicates the number of test cases.
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.
Output
For every test case, you should output "
Case #x: y", where
x indicates the case number and counts from
1 and
y is the result. If there are no frogs in same country, output
−1 instead.
Sample Input
Sample Output
有就输出,没有就-1,代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//大水题!
int main()
{
int T, kase = 1;
cin >> T;
while(T--)
{
char s[1100];
int f[30];//保存上一次字母出现的位置
memset(f, -1, sizeof(f));
int ans = 1<<20;
scanf("%s", s);
int l = strlen(s);
for(int i = 0;i < l; ++i)
{
if(f[s[i]-'a'] != -1 && i - (f[s[i]-'a']) < ans) ans = i - f[s[i]-'a'];
f[s[i]-'a'] = i;
}
printf("Case #%d: ", kase++);
if(ans == 1<<20) cout << -1 << endl;
else cout << ans <<endl;
}
return 0;
}