这题主要就是输出的格式比较繁琐
另外一个需要注意的是,尽量用string类型来操作数据,而不是char,char类型容易出错。
#include <iostream>
#include <algorithm>
#include <algorithm>
using namespace std;
struct Pos{ // 存储字母,及其 在字符串中的位置
string c; // 这里用string 类型不容易出错
int pos;
Pos(){}
Pos(string cc,int p):c(cc),pos(p){}
bool operator< (const Pos& y) const{
if(c>="a"&&c<="z"&&y.c>="0"&&y.c<="9") return true;
if(c>="A"&&c<="Z"&&y.c>="0"&&y.c<="9") return true;
if(c>="0"&&c<="9"&&y.c>="a"&&y.c<="z") return false;
if(c>="0"&&c<="9"&&y.c>="A"&&y.c<="Z") return false;
if(c!=y.c) return c<y.c;
return pos<y.pos;
}
};
struct Output{ // 存储 有重复的字符及其对应的位置 pos: 第一次出现的下标 res: 用于输出的格式化结果串
int pos;
string res;
Output(){}
Output(int p,string r):pos(p),res(r){}
bool operator< (const Output& y) const {
return pos<y.pos;
}
};
string Tran(int x){ // 将数字转换为其对应的字符串形式
string res="";
if(x==0) return "0";
while(x>0){
char temp = x%10 +'0';
res = temp + res;
x/=10;
}
return res;
}
int main(){
string str;
while(cin>>str){
int len = str.size();
Pos arr[101];
Output output[101];
int outNum=0;
for(int i=0;i<len;i++)
arr[i] = Pos(str.substr(i,1),i);
sort(arr,arr+len);
for(int i=1;i<len;i++){
if(arr[i].c==arr[i-1].c){ // 存在重复字符
string res = arr[i-1].c+":" + Tran(arr[i-1].pos); // 这里arr[i-1].c的类型如果是char的话,会出现很奇怪的错误,还是尽量用string来避免吧
int ppp = arr[i-1].pos;
while(arr[i].c==arr[i-1].c&&i<len){
res = res + ","+arr[i].c+":"+Tran(arr[i].pos);
i++;
}
output[outNum++] = Output(ppp,res);
if(i<len) i--;
}
}
sort(output,output+outNum); // 根据第一次出现的下标进行排序
for(int i=0;i<outNum;i++)
cout<<output[i].res<<endl;
}
return 0;
}