题目描述
对给定的一个字符串,找出有重复的字符,并给出其位置,如:abcaaAB12ab12 输出:a,1;a,4;a,5;a,10,b,2;b,11,1,8;1,12, 2,9;2,13。
输入描述:
输入包括一个由字母和数字组成的字符串,其长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据,
按照样例输出的格式将字符出现的位置标出。
1、下标从0开始。
2、相同的字母在一行表示出其出现过的位置。
示例1
输入
abcaaAB12ab12
输出
a:0,a:3,a:4,a:9
b:1,b:10
1:7,1:11
2:8,2:12
题目解析:首先不区分大小写,全部转为小写。两层循环,输出一个字符后,将后方字符串中相同的字符标记为已读。
代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main()
{
string str;
while(cin >> str){
for(int i = 0 ; i < str.size(); i++){
bool flag = false;
if(str[i] == '*'){
continue;
}
for(int j = i + 1; j < str.size(); j++){
if(str[i] == str[j]){
if(flag == false){
cout << str[i] << ":" << i;
flag = true;
}
cout << "," << str[j] << ":" << j;
str[j] = '*'; //如果有重复的,就将他变个符号
}
}
if(flag){
cout << endl; //只有有重复的才会换行,不然会出现空行
}
}
}
return 0;
}
/*使用map会有问题,自动排序,数字会先输出
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main()
{
string str;
map<char,int> mp;
vector<pair<char,int>> vc;
while(cin >> str){
for(int i = 0 ; i < str.size(); i++){
mp[str[i]]++;
}
map<char,int>::iterator it = mp.begin();
for(it; it != mp.end(); it++){
if(it->second > 1){
for(int i = 0; i < str.size(); i++){
if(it->first == str[i]){
vc.push_back(make_pair(it->first,i));
}
}
for(int i = 0; i < vc.size(); i++){
cout << vc[i].first << ":" << vc[i].second;
if(i != (vc.size() - 1)){
cout << ",";
}
}
cout << endl;
vc.clear();
}
}
mp.clear();
}
return 0;
}
*/