问题 B: Friendship of Mouse
时间限制: 1 Sec 内存限制: 64 MB提交: 24 解决: 15
[ 提交][ 状态][ 讨论版]
题目描述
Today in KBW, N mice from different cities are standing in a line. Each city is represented by a lowercase letter. The distance between adjacent mice (e.g. the 1
st and the 2
nd mouse, the N−1
th and the N
thmouse, etc) are exactly 1. Two mice are friends if they come from the same city.
The closest friends are a pair of friends with the minimum distance. Help us find that distance.
The closest friends are a pair of friends with the minimum distance. Help us find that distance.
输入
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 i th character of the string indicates the city of i th mice.
⋅ 1≤T≤50.
⋅ for 80% data, 1≤N≤100.
⋅ for 100% data, 1≤N≤2000.
⋅ the string only contains lowercase letters.
Every test case only contains a string with length N, and the i th character of the string indicates the city of i th mice.
⋅ 1≤T≤50.
⋅ for 80% data, 1≤N≤100.
⋅ for 100% data, 1≤N≤2000.
⋅ the string only contains lowercase letters.
输出
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 mice in same city, output −1 instead.
样例输入
2
abcecba
abc
样例输出
Case #1: 2
Case #2: -1
提示
很简单,如果每次出现一个字符就更新这个字符在map中的位置就可以了,判断一个元素是否出现过可以用map来快速判断
//
// main.cpp
// Friendship of Mouse
//
// Created by 张嘉韬 on 16/9/4.
// Copyright © 2016年 张嘉韬. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
using namespace std;
const int inf=1<<30;
map <char,int> pos;
int main(int argc, const char * argv[]) {
//freopen("/Users/zhangjiatao/Documents/ACM/input.txt","r",stdin);
int T;
scanf("%d",&T);
for(int t=1;t<=T;t++)
{
pos.clear();
string a;
cin>>a;
int minimum=inf;
for(int i=0;i<a.size();i++)
{
char temp=a[i];
if(pos[temp]==0) pos[temp]=i+1;
else
{
minimum=min(minimum,i+1-pos[temp]);
pos[temp]=i+1;
}
}
if(minimum==inf) minimum=-1;
printf("Case #%d: %d\n",t,minimum);
}
return 0;
}