1. 程式人生 > >JAVA語言——字符串排序

JAVA語言——字符串排序

\n 牛客網 collect ray imp pack term question line

題目描述

先輸入你要輸入的字符串的個數。然後換行輸入該組字符串。每個字符串以回車結束,每個字符串少於一百個字符。 如果在輸入過程中輸入的一個字符串為“stop”,也結束輸入。 然後將這輸入的該組字符串按每個字符串的長度,由小到大排序,按排序結果輸出字符串。

輸入描述:

字符串的個數,以及該組字符串。每個字符串以‘\n’結束。如果輸入字符串為“stop”,也結束輸入.

輸出描述:

可能有多組測試數據,對於每組數據,
將輸入的所有字符串按長度由小到大排序輸出(如果有“stop”,不輸出“stop”)。

根據輸入的字符串個數來動態分配存儲空間(采用new()函數)。每個字符串會少於100個字符。
測試數據有多組,註意使用while()循環輸入。

鏈接:https://www.nowcoder.com/questionTerminal/dfeed0e0e4624814b122265e859783b2
來源:牛客網

//package hhhhhhhh;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
 
public class Main
{
    public static void main(String... as)
    {
        Scanner sc = new
Scanner(System.in); while (sc.hasNextInt()) { int n = sc.nextInt() + 1; List<String> list = new ArrayList<>(); while (n-- != 0) { String curr = sc.nextLine(); if (curr.equals("stop"))
break; list.add(curr); } Collections.sort(list, (a, b) -> a.length() - b.length()); for (String each : list) if (!each.equals("")) System.out.println(each); } sc.close(); } }

JAVA語言——字符串排序