两种排序方法

题目描述
考拉有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

import java.io.*;
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(bf.readLine().trim());
        String[] s = new String[n];
        for(int i = 0; i < n; i++){
            s[i] = bf.readLine().trim();
        }
        boolean isLen = getLen(s);
        boolean isLex = getLex(s);
        if(isLen && !isLex) System.out.println("lengths");
        else if(!isLen && isLex) System.out.println("lexicographically");
        else if(isLen && isLex) System.out.println("both");
        else System.out.println("none");
        
    }    
    public static boolean getLen(String[] s){        
        for(int i = 1; i < s.length; i++){
            if(s[i].length() < s[i-1].length()) return false; 
        }
        return true;
    }
    
    public static boolean getLex(String[] s){
        for(int i = 1; i < s.length; i++){
            if(s[i].compareTo(s[i-1]) < 0) return false;
        }
        return true;
    }
}

逻辑是非常简单的,就不分析了,唯一一点就是s[i].compareTo(s[i-1])这个是根据字典排序规则来进行大小写比较。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值