两种排序方法(直接判断)

题目描述

考拉有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


 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.Scanner;
 4 
 5 public class Main {
 6 static public int n ;
 7 static public String[] strs = {"a","aa","bbb"};
 8 static public Boolean lengths = true;
 9 static public Boolean lexicographically = true;
10 static public String f() {
11     for (int i = 1; i < strs.length; i++) {
12         
13         if (lengths) {
14             if (strs[i].length()<strs[i-1].length()) {
15                 lengths = false;
16             }
17         }
18         if (lexicographically) {
19             if (strs[i].compareTo(strs[i-1])<0) {
20                 lexicographically = false;
21             }
22         }
23         if (!lengths&&!lexicographically) {
24             return "none";
25         }
26         
27     }
28     if (lengths&&lexicographically) {
29         return "both";
30     }
31     if (lengths&&!lexicographically) {
32         return "lengths";
33     }
34     if (!lengths&&lexicographically) {
35         return "lexicographically";
36     }
37     return null;
38 }
39 
40 public static void main(String[] args) {
41     Scanner sc = new Scanner(System.in);
42     n = Integer.parseInt(sc.nextLine().trim());
43     strs = new String[n];
44     for (int i = 0; i < n; i++) {
45         strs[i] = sc.nextLine();
46     }
47     
48     System.out.println(f());
49 }
50 }

猜你喜欢

转载自www.cnblogs.com/the-wang/p/8979395.html
今日推荐