题解 | 找位置

找位置

https://www.nowcoder.com/practice/e3b2cc44aa9b4851bdca89dd79c53150

#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
#include <utility>
using namespace std;

struct entry{
    char type;
    int sum;
  //==运算符重载
    bool operator==(const entry& o){
        return type==o.type;
    }
};

pair<char, int> p[100]; //存储每个字符及其对应的下标
char str[105];
vector<entry> s(100); //存储每个字符出现的次数

int main(){ 
    while (cin.getline(str, 100)) { 
        int n=strlen(str);
        for(int i=0;i<n;i++){
            char cc = str[i]; 
            p[i].first=cc;
            p[i].second=i;
            entry e;
            e.type=cc;
		  //重载==运算符,用vector的find函数来查找数组中是否包含某个元素;若不包含则插入,若包含则数量加1;
            auto it = find(s.begin(), s.end(), e);
            if(it==s.end()){ //it==s.end()表示s中不存在当前元素,
                e.sum=1;
                s.push_back(e); //在数组末尾插入
            }else {
                it->sum++;
            }
        }

        pair<char,int> tp;
        tp.second=-1;

        for(auto it:s){
            for(int j=0;j<n;j++){
                if(p[j].first==it.type && it.sum!=1){    
                    if(tp.second!=-1 && p[j].first==tp.first){
                        tp.first=p[j].first;
                        tp.second=p[j].second;
                        printf(",%c:%d",tp.first,tp.second);
                    } else if (tp.second==-1) {
                        tp.first=p[j].first;
                        tp.second=p[j].second;
                        printf("%c:%d",tp.first,tp.second);
                    }else if(tp.second!=-1 && p[j].first!=tp.first){
                        tp.first=p[j].first;
                        tp.second=p[j].second;
                        printf("\n%c:%d",tp.first,tp.second);
                    }         
                }
            }
        }
    }
}

起初想的简单了,以为使用map、set集合就搞定了;结果发现几个坑,自己的基础太不牢固了:

  1. set和map集合会自动排序,取的时候不能按照存的顺序来取;
  2. unorder_set和unorder_map到是不会自动排序,但是使用insert()方法插入数据是基于哈希表实现,插入元素的位置完全由哈希函数决定,也不能按照插入的顺序访问;
  3. 所以最后只能自己定义结构体,并构造vector数组,然后重载==运算符,用vector的find函数来查找数组中是否包含某个元素;若不包含则插入,若包含则数量加1;

对于输出格式也想了半天:

  1. 找到符合条件的元素后,先存到一个临时变量pair<char,int> tp中;
  2. 然后判断这个元素是否(tp.second==-1)是第一个输出的,若是第一个,则开始不加逗号;
  3. 若不是第一个输出的,再判断是不是和上一个输出的符号相同,若相同则加逗号输出;若不相同则加上换行符'\n'后输出;
全部评论

相关推荐

也许是天气_:放在双9简历池里也是中上简历,没人指导一是看不懂,二是可能在偷偷抄你简历亮点。如果大厂0面,多半是卡学历了。我觉得你这情况不愁offer,找工作跟投资一样的,90%的时间都是在等待。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务