描述
对于给定的由大小写字母混合构成的 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;
}
}