首页 > 试题广场 >

字符串排序

[编程题]字符串排序
  • 热度指数:569313 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于给定的由大小写字母混合构成的 n 个单词,输出按字典序从小到大排序后的结果。

【名词解释】
\hspace{15pt}从字符串的第一个字符开始逐个比较,直至发现第一个不同的位置,比较这个位置字符的 Ascii 码,Ascii 码较小(\texttt{`A'} \lt \texttt{`B'} \cdots \lt \texttt{`Z'} \lt \texttt{`a'} \lt \cdots \lt \texttt{`z'})的字符串字典序也较小。

输入描述:
\hspace{15pt}第一行输入一个整数 n \left( 1 \leqq n \leqq 10^3 \right) 代表给定的单词个数。
\hspace{15pt}此后 n 行,每行输入一个长度 1 \leqq {\rm length}(s) \leqq 100,由大小写字母构成的字符串 s,代表一个单词。


输出描述:
\hspace{15pt}一共 n 行,每行输出一个字符串,代表排序后的结果。第一行输出字典序最小的单词。
示例1

输入

11
cap
to
cat
card
two
too
up
boat
boot
AA
Aa

输出

AA
Aa
boat
boot
cap
card
cat
to
too
two
up
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int num = in.nextInt();
        in.nextLine();
        List<String> list = new ArrayList<>();
        for(int i=0;i<num;i++){
            list.add(in.next());
        }
        Collections.sort(list);
        for(String str : list){
            System.out.println(str);
        }
    }
}
发表于 2025-06-15 11:21:51 回复(0)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = in.nextInt();
        List list = new ArrayList<String>();
        for(int i=0 ; i<count; i++){
            String str =in.next();
            list.add(str);
        }
        Collections.sort(list);
        list.forEach(System.out::println);
       
    }
}

发表于 2025-05-18 21:35:47 回复(0)
采用最小优先队列排序
import java.util.Scanner;
import java.util.PriorityQueue;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       PriorityQueue<String> queue=new PriorityQueue<>();
       int len=in.nextInt();
       for(int i=0;i<len;i++){
            String str=in.next();
            queue.add(str);
       }
       while(!queue.isEmpty()){
            System.out.println(queue.poll());
       }
       in.close();
    }
}


发表于 2025-03-21 23:26:23 回复(0)
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int len = in.nextInt();
        in.nextLine();
        List<String> list = new ArrayList<>();
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            list.add(a);
        }
        Collections.sort(list);
        for(String str:list){
            System.out.println(str);
        }
        in.close();
    }
发表于 2025-02-05 18:06:46 回复(0)
Arrays.sort()  排序

发表于 2025-01-26 21:43:08 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(); // 读取字符串的数量
        in.nextLine(); // 读取换行符

        String[] strings = new String[n]; // 创建字符串数组

        for (int i = 0; i < n; i++) {
            strings[i] = in.nextLine(); // 读取每个字符串
        }

        Arrays.sort(strings); // 使用Arrays类的sort方法对字符串进行排序

        for (String str : strings) {
            System.out.println(str); // 输出排序后的字符串
        }

        in.close(); // 关闭扫描器
    }
}

发表于 2024-10-18 23:23:18 回复(0)
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(), i = 0, j;
        String[] dict = new String[n];
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) {
            dict[i++] = in.next();
        }
        // 依照自己编写的比较逻辑进行排序
        for (i = 0; i < n - 1; i++) {
            for (j = i + 1; j < n; j++) {
                if (compare(dict[i], dict[j]) > 0) {
                    String t = dict[i];
                    dict[i] = dict[j];
                    dict[j] = t;
                }
            }
        }
        for (i = 0; i < n; i++) {
            System.out.println(dict[i]);
        }
    }
    public static int compare(String a, String b) {
        /* 字符串字典比较,返回1,-1或0 */
        int len = a.length() > b.length()? b.length(): a.length();
        /* 终止条件:有一个子串被消耗完 */
        if (len == 0) {
            if (a.length() == b.length()) {
                return 0;
            } else if (a.length() > 0) {
                return 1;
            } else {
                return -1;
            }
        }
        if (a.charAt(0) == b.charAt(0)) {
            /* 按照递归思想,当前一位相同时比较剩余的子串 */
            return compare(a.substring(1), b.substring(1));
        } else if (a.charAt(0) > b.charAt(0)) {
            return 1;
        } else {
            return -1;
        }
    }
}
发表于 2024-09-17 10:33:41 回复(0)
三种写法:
用Arrays.sort()方法双轴排序
用ArrayList的sorted方法中的compareTo排序
用ArrayList中的sorted方法中的Comparator.naturalOrder()排序。
方法一:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
        // System.out.println("请输入要比较的单词数目:");
        int n = sc.nextInt();
        String[] strings = new String[n];
        for (int i = 0; i < n; i++) {
            //System.out.println("请输入要比较的单词:");
            strings[i] = sc.next();
        }
        Arrays.sort(strings);

        for (String string : strings) {
            System.out.println(string);
        }

        sc.close();
    }
}
方法二:

//  Scanner sc = new Scanner(System.in);
//        List<String> wordList = new ArrayList<>();
//        System.out.println("请输入要排序的字符串的个数:");
//        int n = sc.nextInt();
//        for (int i = 0; i < n; i++) {
//            System.out.println("请输入单词:");
//            String word = sc.next();
//            wordList.add(word);
//        }
//        wordList.sort(String::compareTo);
//        wordList.forEach(System.out::println);


发表于 2024-09-13 14:39:16 回复(0)
import java.util.Scanner;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int size = Integer.parseInt(in.nextLine());
        String[] Set = new String[size];
        for (int times = 0; times < size; times++) {
            Set[times]=in.nextLine();
        }
        Arrays.sort(Set);
        // 注意 hasNext 和 hasNextLine 的区别
        for (String tmp : Set) {
            System.out.println(tmp);
        }
    }
}

发表于 2024-09-12 23:53:33 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        String[] str =new String[n];
        for(int i=0;i<n;i++){
            str[i]=in.next();
        }
        
        for(int i=0;i<n;i++){
            for(int j=0;j<n-i-1;j++){
                if(str[j].compareTo(str[j+1])>0){
                    String temp;
                    temp=str[j];
                    str[j]=str[j+1];
                    str[j+1]=temp;
                }
            }
        }
        for(String word: str){
            System.out.println(word);
        }
    }
}

发表于 2024-07-28 19:31:58 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        String[] arr = new String[rows];
        for (int i = 0; i < rows; i++) {
            arr[i] = scanner.next();
        }
        Arrays.sort(arr);
        for (String word : arr) {
            System.out.println(word);
        }
    }
}

发表于 2024-07-03 19:21:26 回复(2)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String line;
        int cnt = 0;
        int linecnt = 1;
        String[] array= null;;
        // 保存数据
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            if(linecnt == 1){
                cnt = in.nextInt();
                in.nextLine();
                array = new String[cnt];
            }else{
                array[linecnt - 2] = in.nextLine();
            }



            if(linecnt == cnt + 1){
                break;
            }

            linecnt ++;
        }

        // 排序
        String temp;
        for(int i = 0; i<array.length; i ++){
            for(int j = 0; j < array.length - i - 1;j++){
                if(array[j].compareTo(array[j + 1]) > 0){
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }

        //输出(或在排序时找出最小的依次输入,减少一次for过程)
        for(String e :array){
            System.out.println(e);
        }
    }
}

发表于 2024-06-20 01:30:11 回复(0)
import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            in.nextLine();
            //count 最长字符串长度
            int count = 0;
            //strs 字符串组
            String[] strs = new String[n];
            for (int i = 0; i < n; i++) {
                strs[i] = in.nextLine();
                if (strs[i].length() > count) {
                    count = strs[i].length();
                }
            }
            //位数
            for (int i = 0; i < count; i++) {
                int[] boot = new int[52];
                String[][] tong = new String[52][n];
                String[] ru = new String[n];
                for (String item : strs) {
                    if (item.length() < count - i) {
                        tong[0][boot[0]] = item;
                        boot[0]++;
                    } else {
                        int ins = item.charAt(count - 1 - i) >= 'a' ? item.charAt(
                                      count - 1 - i) - 'a' + 26 : item.charAt(count - 1 - i) - 'A';
                        tong[ins][boot[ins]] = item;
                        boot[ins]++;
                    }
                }
                int index = 0;
                for (int j = 0; j < 52; j++) {
                    if (boot[j] == 0) {
                        continue;
                    }
                    for (int k = 0; k < boot[j]; k++) {
                        ru[index++] = tong[j][k];
                    }
                }
                System.arraycopy(ru, 0, strs, 0, n);
            }

            for (String item : strs) {
                System.out.println(item);
            }
        }
    }
}

发表于 2024-06-13 21:34:52 回复(1)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            String[] str = new String[n];
           
            for(int i=0;i<n;++i){
                str[i]=in.next();
            }
            Arrays.sort(str);
            for(int i=0;i<str.length;i++){
                System.out.println(str[i]);
            }
        }
    }
}
发表于 2024-05-07 16:39:49 回复(0)
我用
while (in.hasNextLine()) { // 注意 while 处理多个 case
            String b = in.nextLine();
            if(b != null && b != "") {
                map.put(b,0);      
            }               
}
剔除掉空字符串,结果神奇的来了:调试显示是正确的,第一行不是空;自测运行第一行却是空的。
编辑于 2024-04-25 09:34:19 回复(0)
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = Integer.valueOf(in.nextLine());
        ArrayList<String> arr = new ArrayList<>();
        for(int i=0;i<num;i++) {
            arr.add(in.nextLine());
        }

        Collections.sort(arr);
        for(String str:arr) {
            System.out.println(str);
        }
    }
}

发表于 2024-04-24 10:39:40 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            String str = sc.next();
            list.add(str);
        }
        Collections.sort(list);
        for (String s : list) {
            System.out.println(s);
        }
    }
}
编辑于 2024-04-15 19:56:33 回复(0)
这么做应该没问题吧
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        TreeMap<String, String> map = new TreeMap<String, String>();
        int i = Integer.parseInt( in.nextLine());
        while (in.hasNextLine()) {
            String str = in.nextLine();
            String value = String.valueOf(str);
            if (str.isEmpty()) {
                break;
            }
            //用treeMap 自动排序,让key和value 相同插入,
            //因为不能去掉重复的值,所以在有重复key出现时拼接1;
            while (map.containsKey(str)) {
                str = str + "1";
            }
            if (!map.containsKey(str)) {
                map.put(str, value);
            }
        }
        for (Map.Entry<String, String> o : map.entrySet() ) {
            System.out.println(o.getValue());
        }
    }
}
发表于 2024-04-06 12:26:19 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        List<String> r = new ArrayList();
        while (n -- > 0) {
            r.add(in.next());
        }
        Collections.sort(r);
        r.forEach(System.out::println);
    }
}

编辑于 2024-03-16 16:55:20 回复(0)
暴力解法。。。。。
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            String [] str = new String[a];
            for (int i = 0; i < a; i++) {
                str[i] = in.next();
            }
            // 使用选择排序
            for (int i = 0; i < a; i++) {
                int minIndex = i;
                for (int j = i + 1; j < a; j++) {
                    if (!isSwamp(str[minIndex], str[j])) {
                        minIndex = j;
                    };
                }
                if (minIndex != i) {
                    String temp = str[i];
                    str[i] = str[minIndex];
                    str[minIndex] = temp;
                }
            }
            for (String str1 : str) {
                System.out.println(str1);
            }
        }
    }

    public static boolean isSwamp(String word1, String word2) {
        int strLength = Math.min(word1.length(), word2.length());
        for (int i = 0; i < strLength; i++) {
            // 字符一比较出大小,就结束循环
            if (word1.charAt(i) < word2.charAt(i)) {
                return true;
            } 
            if (word2.charAt(i) < word1.charAt(i)){  
                return false;                          
            }
        }
        // 遍历部分字符相同,则比较长度,长度较大的必定排在后面
        return word1.length() > word2.length()? false:true;
    }
}

发表于 2024-03-15 06:21:23 回复(0)