思路:dp[i]表示所求答案,则dp[pos[str[i]-'a']] = min(dp[pos[str[i]-'a']], i - pos[str[i]-'a']) ; dp[i] = i - pos[str[i]-'a'];pos 记录与当前字母相同的且离当前位置最近的字母的位置。
/*
USER_ID: test#wangzhili
PROBLEM: 94
SUBMISSION_TIME: 2014-04-02 22:19:32
*/
#include<iostream>
#include<cstdio>
#include<climits>
#include<cstring>
#define MAX 100005
using namespace std;
char str[MAX], op[20], cc[2];
int pos[30], dp[MAX];
int main(){
int c, n, pp;
scanf("%d", &c);
while(c--){
memset(str, 0, sizeof(str));
memset(pos, -1, sizeof(pos));
for(int i = 0;i < MAX;i ++) dp[i] = INT_MAX;
scanf("%s", str);
int len = strlen(str);
for(int i = 0;i < len;i ++){
if(pos[str[i]-'a'] != -1){
dp[pos[str[i]-'a']] = min(dp[pos[str[i]-'a']], i - pos[str[i]-'a']);
dp[i] = i - pos[str[i]-'a'];
}
pos[str[i]-'a'] = i;
}
scanf("%d", &n);
while(n--){
memset(op, 0, sizeof(op));
scanf("%s", op);
if(!strcmp("INSERT", op)){
scanf("%s", cc);
str[len++] = cc[0];
if(pos[cc[0]-'a'] != -1){
dp[pos[cc[0]-'a']] = min(dp[pos[cc[0]-'a']], len-1-pos[cc[0]-'a']);
dp[len-1] = len-1-pos[cc[0]-'a'];
}
pos[cc[0]-'a'] = len-1;
}else{
scanf("%d", &pp);
if(dp[pp] <= MAX) printf("%d\n", dp[pp]);
else printf("-1\n");
}
}
}
return 0;
}