题解 | #找位置#
找位置
http://www.nowcoder.com/practice/e3b2cc44aa9b4851bdca89dd79c53150
/*我的思路是,用一个结构体存储出现过的字符和他的位置,位置用String字符串实现。
当这个字符串的长度为1时表明其只出现过一次,不打印,否则依次打印*/
#include <bits/stdc++.h>
using namespace std;
struct A //存储输入字符串中的字符和其出现过的位置
{
char num;
string pos;
};
int main()
{
string str;
while(cin>>str)
{
int n=str.size();
A temp[n];
int k=0; //记录出现过的字符的数量;
for(int i=0; i<n; i++) //对出现过的所有字符进行存储并记录其位置
{
bool flag=true;
for(int j=0; j<k; j++)
{
if(str[i]==temp[j].num)
{
temp[j].pos+=i; //记录位置
flag=false;
break;
}
}
if(flag)
{
temp[k].num=str[i];
temp[k++].pos=i;
}
}
for(int i=0; i<k; i++)
{
if(temp[i].pos.size()==1) continue; //只出现过一次的字符不打印
printf("%c:%d",temp[i].num,temp[i].pos[0]);
for(int j=1; j<temp[i].pos.size(); j++)
printf(",%c:%d",temp[i].num,temp[i].pos[j]);
cout<<endl;
}
}
}
