题目——找位置(字符串、查找)

题目链接

这题主要就是输出的格式比较繁琐

另外一个需要注意的是,尽量用string类型来操作数据,而不是char,char类型容易出错。

#include <iostream>
#include <algorithm>
#include <algorithm>
using namespace std;
struct Pos{   // 存储字母,及其 在字符串中的位置
    string c;  // 这里用string 类型不容易出错
    int pos;
    Pos(){}
    Pos(string cc,int p):c(cc),pos(p){}
    bool operator< (const Pos& y) const{
        if(c>="a"&&c<="z"&&y.c>="0"&&y.c<="9") return true;
        if(c>="A"&&c<="Z"&&y.c>="0"&&y.c<="9") return true;
        if(c>="0"&&c<="9"&&y.c>="a"&&y.c<="z") return false;
        if(c>="0"&&c<="9"&&y.c>="A"&&y.c<="Z") return false;
        if(c!=y.c) return c<y.c;
        return pos<y.pos;
    }
};
struct Output{   // 存储   有重复的字符及其对应的位置  pos: 第一次出现的下标  res: 用于输出的格式化结果串
    int pos;
    string res;
    Output(){}
    Output(int p,string r):pos(p),res(r){}
    bool operator< (const Output& y) const {
        return pos<y.pos;
    }
};
string Tran(int x){   // 将数字转换为其对应的字符串形式
    string res="";
    if(x==0) return "0";
    while(x>0){
        char temp = x%10 +'0';
        res = temp + res;
        x/=10;
    }
    return res;
}
int main(){
    string str;
    while(cin>>str){
        int len = str.size();
        Pos arr[101];
        Output output[101];
        int outNum=0;
        for(int i=0;i<len;i++)
            arr[i] = Pos(str.substr(i,1),i);
        sort(arr,arr+len);
        for(int i=1;i<len;i++){
            if(arr[i].c==arr[i-1].c){   // 存在重复字符
                string res = arr[i-1].c+":" + Tran(arr[i-1].pos);   // 这里arr[i-1].c的类型如果是char的话,会出现很奇怪的错误,还是尽量用string来避免吧
                int ppp = arr[i-1].pos;
                while(arr[i].c==arr[i-1].c&&i<len){
                    res = res + ","+arr[i].c+":"+Tran(arr[i].pos);
                    i++;
                }
                output[outNum++] = Output(ppp,res);
                if(i<len) i--;
            }
        }
        sort(output,output+outNum);   // 根据第一次出现的下标进行排序
        for(int i=0;i<outNum;i++)
            cout<<output[i].res<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值