字符串排序

字符串排序

http://www.nowcoder.com/questionTerminal/5190a1db6f4f4ddb92fd9c365c944584

运用sort排序,定义符合规则的比较对象

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

// 字符的小写优先级及位置优先级
struct CharPos{
    char ch; // 源字符串
    int alpha; // 小写字符的ascii码
    size_t pos; // 源字符串位置
    bool bCap; // 是否大写
    CharPos()=default;
    CharPos(char c, size_t p):ch(c), alpha(tolower(c)), pos(p){
        if(isupper(c)){
            bCap=true;
        }
    }
};

struct Compare{
    bool operator()(const CharPos& cp1, const CharPos& cp2){
        if(cp1.alpha==cp2.alpha){
            if(cp1.bCap==cp2.bCap){
                return cp1.pos<cp2.pos;
            }
        }else{
            return cp1.alpha<cp2.alpha;
        }
    }
};

int main(){
    string str;
    while(getline(cin, str)){
        vector<CharPos> cpvec;
        for(size_t i=0;i<str.size();++i){
            char c=str[i];
            if(isalpha(c)){
                cpvec.emplace_back(c, i);
            }
        }
        sort(cpvec.begin(), cpvec.end(), Compare());
        string res;
        size_t cpvec_ind=0;
        for(size_t i=0;i<str.size();++i){
            char c=str[i];
            if(!isalpha(c)){
                res+=c;
            }else{
                res+=cpvec[cpvec_ind].ch;
                ++cpvec_ind;
            }
        }
        cout<<res<<'\n';
    }
    return 0;
}
全部评论

相关推荐

10-16 15:48
算法工程师
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

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