当前位置:网站首页>【Day_08 0426】两种排序方法
【Day_08 0426】两种排序方法
2022-08-01 17:40:00 【安河桥畔】
两种排序方法
题目来源
牛客网:两种排序方法
题目描述
考拉有n个字符串字符串,任意两个字符串长度都是不同的。考拉最近学习到有两种字符串的排序方法: 1.根据字符串的字典序排序。例如:
“car” < “carriage” < “cats” < "doggies < “koala”
2.根据字符串的长度排序。例如:
“car” < “cats” < “koala” < “doggies” < “carriage”
考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。
输入描述
输入第一行为字符串个数n(n ≤ 100) 接下来的n行,每行一个字符串,字符串长度均小于100,均由小写字母组成
输出描述
如果这些字符串是根据字典序排列而不是根据长度排列输出"lexicographically",
如果根据长度排列而不是字典序排列输出"lengths",
如果两种方式都符合输出"both",否则输出"none"
示例
输入
3
a
aa
bbb输出
both
思路分析
- 要输入多个字符串,所以使用vector<string>来进行保存
- 遍历vector,比较前后两个字符串的长度和大小
- C语言中字符串比较用strcmp函数,C++中可以直接使用’>'比较两个字符串的大小
代码展示
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> ar;
int n = 0;
cin >> n;
ar.resize(n);
for (int i = 0; i < n; i++)
{
cin >> ar[i];
}
bool lex = true;
bool lengths = true;
for (int i = 0; i < n - 1; i++)
{
//lengths
if (ar[i].size() > ar[i + 1].size())
{
lengths = false;
}
//lexicographically
if (ar[i] > ar[i + 1])
{
lex = false;
}
//如果两种排序都不是,提前break
if (!(lengths) && !(lex))
{
break;
}
}
if (lex && lengths)
{
cout << "both" << endl;
}
else if (lex && !(lengths))
{
cout << "lexicographically" << endl;
}
else if (lengths && !(lex))
{
cout << "lengths" << endl;
}
else
{
cout << "none" << endl;
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
ROS2系列知识(7):用rqt_console查看日志logs
SQL的substring_index()用法——MySQL字符串截取
SQL函数 TO_CHAR(一)
金仓数据库 OCCI迁移指南(3. KingbaseES的OCCI特性支持)
M1芯片电脑安装cerebro
Are online account opening commissions reliable? Is online account opening safe?
加州大学|通过图抽象从不同的第三人称视频中进行逆强化学习
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
广汽埃安“弹匣电池”,四大核心技术,出行安全保障
LeaRun.net快速开发动态表单
金仓数据库 KingbaseES V8.3 至 V8.6 迁移最佳实践(4. V8.3 到 V8.6 数据库移植实战)
网上开户佣金万一靠谱吗,网上开户安全吗
ROS2系列知识(6):Action服务概念
The anxiety of the post-90s was cured by the vegetable market
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
C# LibUsbDotNet 在USB-CDC设备的上位机应用
B011 - 基于51的多功能指纹智能锁
2022年深圳市促进大健康产业集群高质量发展的若干措施
访问域名直接访问wordpress
主流小程序框架性能分析