Friendship of Frog

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzyws739307453/article/details/82802226

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

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

2

abcecba

abc

Sample Output

Case #1: 2

Case #2: -1

Solving Ideas

这道题就是让求相同两字符下标之差。

可以先用一个数组村每个字符的位置,初始化设为-1,当出现相同的字符更新minn。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int inf = 99999999;
int main()
{
	char str[1010];
	int vis[30], len, minn, k, t;
	scanf("%d", &t);
	for (int k = 1; k <= t; k++)
	{
		scanf("%s", str + 1);
		minn = inf;
		len = strlen(str + 1);
		memset(vis, -1, sizeof(vis));
		for (int i = 1; i <= len; i++)
		{
			if (vis[str[i] - 'a'] != -1)
				minn = min(minn, i - vis[str[i] - 'a']);
			vis[str[i] - 'a'] = i;
		}
		if (minn == inf)
			minn = -1;
		printf("Case #%d: %d\n", k, minn);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lzyws739307453/article/details/82802226