两种排序方法(字符串+排序+STL)

时间限制:1秒  空间限制:32768K  热度指数:12801
 算法知识视频讲解

题目描述

考拉有n个字符串字符串,任意两个字符串长度都是不同的。考拉最近学习到有两种字符串的排序方法: 1.根据字符串的字典序排序。例如:
"car" < "carriage" < "cats" < "doggies < "koala"
2.根据字符串的长度排序。例如:
"car" < "cats" < "koala" < "doggies" < "carriage"
考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。

输入描述:

输入第一行为字符串个数n(n ≤ 100)
接下来的n行,每行一个字符串,字符串长度均小于100,均由小写字母组成

输出描述:

如果这些字符串是根据字典序排列而不是根据长度排列输出"lexicographically",

如果根据长度排列而不是字典序排列输出"lengths",

如果两种方式都符合输出"both",否则输出"none"
示例1

输入

3
a
aa
bbb

输出

both

【分析】排序+STL

        这里涉及到了对字符串的两种排序方法:按字典序排序、按字符串长度排序。为了进行比较,可使用结构体保存字符串内容,并将输入做两个"副本",一个用作按字典序排序,另一个用作字符串长度排序,排序后逐一比对即可。最后注意分4种情况讨论。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=105;
const int maxl=105;
int n;
struct str
{
	char content[maxl];
} tmp[maxn],s1[maxn],s2[maxn];
using namespace std;
//按字典序排序 
bool cmp1(struct str s,struct str t)
{
	return (strcmp(s.content,t.content)<0);
}
//按字符串长度排序 
bool cmp2(struct str s,struct str t)
{
	return (strlen(s.content)<strlen(t.content));
}
int main()
{
	int i;
	int lex=1,len=1; //标记lex=1-按字典序排序 len=1-按字符串长度排序 
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%s",tmp[i].content);
		//copy副本 
		strcpy(s1[i].content,tmp[i].content);
		strcpy(s2[i].content,tmp[i].content);
	}
	//排序 
	sort(s1,s1+n,cmp1);
	sort(s2,s2+n,cmp2);
	//逐一比对 
	for(i=0;i<n;i++)
	{
		if(strcmp(tmp[i].content,s1[i].content)!=0)
			lex=0;
		if(strcmp(tmp[i].content,s2[i].content)!=0)
			len=0;
	}
	//4种情况讨论 
	if(lex==1 && len==1)
		printf("both\n");
	else if(lex==1)
		printf("lexicographically\n");
	else if(len==1)
		printf("lengths\n");
	else
		printf("none\n");
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值