统计字符位置

题目描述

题目描述
对给定的一个字符串,找出有重复的字符,并给出其位置,如: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<stdlib.h>
#include<vector>
#include<iostream>
using namespace std;
struct node{          //代表每个字符
    char ch;
    vector<int> pos;
};
typedef node* no;
vector<no> s;         //保存不同字符的信息
int fin(char cha){
    for(int i=0; i<s.size(); i++){
        if(s[i]->ch == cha){
            return i;
        }
    }
    return -1;
}
int main(){
    string  str;
    while(cin>>str){
        s.clear();            //每次都要清空
        int len = str.length();
        for(int i=0; i<len; i++){
            if(fin(str[i])==-1){     //没有这个字符信息 添加
                no temp = new node;
                temp->ch = str[i];
                temp->pos.push_back(i);
                s.push_back(temp);
            }
            else{
                s[fin(str[i])]->pos.push_back(i);   //已有这个字符 添加位置
            }
        }
        for(int i=0; i<s.size(); i++){
            if(s[i]->pos.size()>1){
                for(int j=0; j<s[i]->pos.size(); j++){
                    if(!j)
                        cout<<s[i]->ch<<":"<<s[i]->pos[j];
                    else
                        cout<<","<<s[i]->ch<<":"<<s[i]->pos[j];
                }
                cout<<endl;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_34328764/article/details/80157495