找位置

题目描述
对给定的一个字符串,找出有重复的字符,并给出其位置,如: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;
}  

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值