华为机试:字串的连接最长路径查找

这个题更应该叫做字符串字典序排序

题目描述

给定n个字符串,请对n个字符串按照字典序排列。

输入描述:

输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。

输出描述:

数据输出n行,输出结果为按照字典序排列的字符串。
示例1

输入

9
cap
to
cat
card
two
too
up
boat
boot

输出

boat
boot
cap
card
cat
to
too
two
up

 

Java:傻子似的,重写Arrays.sort()中的Comparator。时间消耗为48ms,空间消耗9492K,消耗同下。

 1 import java.util.Arrays;
 2 import java.util.Comparator;
 3 import java.util.Scanner;
 4 
 5 public class Main {
 6     
 7     public static void main(String[] args) {
 8         Scanner sc=new Scanner(System.in);
 9         while(sc.hasNext()){
10             int num = sc.nextInt();
11             sc.nextLine();
12             String[] s = new String[num];
13             for(int i = 0; i < num; i++){
14                 s[i] = sc.nextLine();
15             }
16             Arrays.sort(s, new Comparator<String>(){
17 
18                 @Override
19                 public int compare(String o1, String o2) {
20                     for(int i = 0; (i < o1.length() && i < o2.length()); i++){
21                         char ch1 = o1.charAt(i);
22                         char ch2 = o2.charAt(i);
23                         if(ch1>ch2){
24                             return 1;
25                         }
26                         else if(ch1 < ch2){
27                             return -1;
28                         }
29                     }
30                     if(o1.length() > o2.length()){
31                         return 1;
32                     }
33                     else{
34                         return -1;
35                     }                    
36                 }
37                 
38             });
39             
40             for(int i=0; i<s.length;i++){
41                 System.out.println(s[i]);
42             }
43         }
44         sc.close();
45     }
46     
47 }

Java:直接用sort

 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 
 4 public class Main {
 5     
 6     public static void main(String[] args) {
 7         Scanner sc=new Scanner(System.in);
 8         while(sc.hasNext()){
 9             int num = sc.nextInt();
10             sc.nextLine();
11             String[] s = new String[num];
12             for(int i = 0; i < num; i++){
13                 s[i] = sc.nextLine();
14             }
15             Arrays.sort(s);
16             
17             for(int i=0; i<s.length;i++){
18                 System.out.println(s[i]);
19             }
20         }
21         sc.close();
22     }
23     
24 }

 

posted @ 2017-09-22 03:59  zdtiio  阅读(240)  评论(0编辑  收藏  举报