java题目 字符串排序

 

描述

给定 n 个字符串,请对 n 个字符串按照字典序排列。
 
数据范围: 1 ≤ n ≤1000   ,字符串长度满足 1 ≤ len 100 

输入描述:

输入第一行为一个正整数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

方法一

 1 import java.util.*;
 2  
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner in = new Scanner(System.in);
 6         List<String> res=new ArrayList<>();
 7  
 8         int n=Integer.parseInt(in.nextLine());
 9         for(int i=0;i<n;i++){
10             res.add(in.nextLine());
11         }
12         Collections.sort(res);  //Collections.sort对list进行正序排列
13         for(String s:res){
14             System.out.println(s);
15         }
16     }
17 }

 

方法二

 1 import java.util.*;
 2 import java.io.*;
 3 
 4 public class Main{
 5     public static void main(String[] args) throws IOException {
 6         BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
 7         int count = Integer.parseInt(bf.readLine());
 8         String[] result = new String[count];
 9         for (int i =0; i<count; i++) {
10             result[i] = bf.readLine();
11         }
12         StringBuilder sb = new StringBuilder();
13         Arrays.sort(result);
14         for (String s : result) {
15             sb.append(s).append('\n');
16         }
17         System.out.println(sb.toString());
18     }
19 }

 

posted @ 2022-02-23 23:12  海漠  阅读(196)  评论(0编辑  收藏  举报