题解 | 找位置
找位置
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集合就搞定了;结果发现几个坑,自己的基础太不牢固了:
- set和map集合会自动排序,取的时候不能按照存的顺序来取;
- unorder_set和unorder_map到是不会自动排序,但是使用insert()方法插入数据是基于哈希表实现,插入元素的位置完全由哈希函数决定,也不能按照插入的顺序访问;
- 所以最后只能自己定义结构体,并构造vector数组,然后重载==运算符,用vector的find函数来查找数组中是否包含某个元素;若不包含则插入,若包含则数量加1;
对于输出格式也想了半天:
- 找到符合条件的元素后,先存到一个临时变量pair<char,int> tp中;
- 然后判断这个元素是否(tp.second==-1)是第一个输出的,若是第一个,则开始不加逗号;
- 若不是第一个输出的,再判断是不是和上一个输出的符号相同,若相同则加逗号输出;若不相同则加上换行符'\n'后输出;