题解 | #找位置#

找位置

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

#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct statis{
    int count;
    vector<int> index;//定义迭代器存储对应下标
};
int main() {
    string str;
    while(cin>>str){
        map<char,statis> mp;//定义散列表,存储字符-统计对应关系
        for(int i=0;i<str.length();i++){
            if(!mp[str[i]].count) mp[str[i]].count=1;
            else mp[str[i]].count++;
            //迭代器使用头插法,方便输出下标时按序从尾部弹出
            mp[str[i]].index.insert(mp[str[i]].index.begin(),i);
        }
        for(int i=0;i<str.length();i++){
            if(mp[str[i]].count>1){
                cout<<str[i]<<":"<<i;//输出结构控制:第一次只输出数对,后面的每对前面都带一个逗号
                mp[str[i]].index.pop_back();
                for(int j=1;j<mp[str[i]].count;j++){//注意j边界,不要写成index.size(),那样是错的
                    cout<<","<<str[i]<<":"<<mp[str[i]].index.back();
                    mp[str[i]].index.pop_back();
                }
                mp[str[i]].count=-1;
                cout<<endl;
            }
        }
    }
    return 0;
}

全部评论

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
找到实习了&nbsp;给了150一天&nbsp;但是说是低代码&nbsp;值得去吗
码农索隆:是在没实习,可去,待个一两周,不行就润呗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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