题目描述:
对给定的一个字符串s,找出有重复的字符,并给出其位置,如:abcaaAB12ab12
输出:a,0;a,3;a,4;a,9,b,1;b,10,1,7;1,11, 2,8;2,12。
思路:用一个数组tag[]把相同的字符连接起来 , 例如:tag[]=3 10 2 4 9 5 6 11 12 9 10 11 12
用数组v[]来标识s[]是否被访问过,
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
char s[110];
int tag[110],vis[110],v[110];
while(scanf("%s",s)==1)
{
int n=strlen(s);
for(int i=0;i<n;i++)
{
tag[i]=i;
vis[i]=0;
v[i]=0;
}
for(int i=0;i<n-1;i++)
{
int temp=i;
for(int j=i+1;j<n;j++)
{
///if(s[j]==s[i] && tag[j]==j)
/**
不能用tag[j]==j来判断s[j]是否被串起来了
因为最后一个最是满足tag[j]==j的条件
*/
if(s[j]==s[i]&&v[j]==0)
{
tag[temp]=j;
temp=j;
v[j]=1;
}
}
}
for(int i=0;i<n-1;i++)
{
if(tag[i]!=i && vis[i]==0)
{
printf("%c:%d",s[i],i);
int temp=i;
while(tag[temp]!=temp)
{
vis[temp]=1;
printf(",%c:%d",s[i],tag[temp]);
temp=tag[temp];
}
printf("\n");
}
}
}
return 0;
}