HJ14 字符串排序

描述

对于给定的由大小写字母混合构成的 nn 个单词,输出按字典序从小到大排序后的结果。

从字符串的第一个字符开始逐个比较,直到找到第一个不同的位置,通过比较这个位置字符对应的 AsciiAscii 码( A<⋯<Z<a<⋯<zA<⋯<Z<a<⋯<z )得出字符串的大小,称为字典序比较。

输入描述:

第一行输入一个整数 n(1≦n≦1000)n(1≦n≦1000) 代表给定的单词个数。
此后 nn 行,每行输入一个长度 1≦length(s)≦1001≦length(s)≦100 ,由大小写字母混合构成的字符串 ss ,代表一个单词。

输出描述:

输出 nn 行,每行输出一个字符串,代表排序后的结果。第一行输出字典序最小的单词。

示例1

输入:

11
cap
to
cat
card
two
too
up
boat
boot
AA
Aa

复制输出:

AA
Aa
boat
boot
cap
card
cat
to
too
two
up

用到了有序集合multiset,自定义小于号运算符重载。

#include <iostream>
#include <set>
#include <vector>
using namespace std;
class Node
{
public:
    Node(string s):s_(s),length_(s.size()){}
    bool operator<(const Node& node) const
    {
        int minLen = min(this->length_ , node.length_);
        for(int i = 0;i < minLen;i++)
        {
            if(this->s_[i] < node.s_[i])
            {
                return true;
            }
            else if(this->s_[i] > node.s_[i]) 
            {
                return false;
            }           
        }
        
        return this->length_ < node.length_;
    }

    string s_;
    size_t length_;
};
int main() {
    multiset<Node> stringNode;
    string ss;
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>ss;
        Node node(ss);
        stringNode.insert(node);
    }

    for(const Node& str: stringNode)
    {
        cout<<str.s_<<endl;
    }

}

好吧,看了别人的代码之后,发现string类型之间的比较,直接就是字典序,这下小丑了。

#include <iostream>
#include <set>
#include <vector>
using namespace std;
class Node
{
public:
    Node(string s):s_(s){}
    bool operator<(const Node& node) const
    {
        return this->s_ < node.s_;       
    }
    string s_;
};
int main() {
    multiset<Node> stringNode;
    string ss;
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>ss;
        Node node(ss);
        stringNode.insert(node);
    }

    for(const Node& str: stringNode)
    {
        cout<<str.s_<<endl;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值