用unordered_map<string, vector>储存字符及其出现的位置序列,结合vector记录不同字符的先后位置。
#include<bits/stdc++.h>
using namespace std;
int main(){
string str, s;
unordered_map<string, vector<int>> res;
vector<string> keys;
while(cin >> str){
res.clear();
keys.clear();
for(int i = 0; i < str.size(); i++){
s = str[i];
if(res.count(s) == 0){
keys.push_back(s);
res.emplace(s, vector<int>{i});
}else{
res[s].push_back(i);
}
}
for(auto iter = keys.begin(); iter != keys.end(); iter++){
if(res[*iter].size() == 1)continue;
for(int i = 0; i < res[*iter].size(); i++){
cout << *iter << ':' << res[*iter][i];
if(i < res[*iter].size()-1)cout << ',';
else cout << endl;
}
}
}
return 0;
}