Day12:字符串排序

101 阅读1分钟

描述

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

数据范围: 1 \le n \le 1000 \1≤n≤1000  ,字符串长度满足 1 \le len \le 100 \1≤len≤100 

输入描述:

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

输出描述:

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

题源:字符串排序_牛客题霸_牛客网 (nowcoder.com)

示例1

输入:

9
cap
to
cat
card
two
too
up
boat
boot

输出:

boat
boot
cap
card
cat
to
too
two
up

可以利用库函数sort来实现,思路很简单,下面是完整代码:

c++:

#include <string>
using namespace std;
#include <algorithm>
int main(){	
	int n;
	cin >> n;
	string word[1001];
	for (int i = 0; i < n; i++){
		cin >> word[i];
		
	}
	sort(word , word+n);
	for (int i = 0; i < n; i++){
		cout << word[i] << endl;
	}
}`

Java:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] word = new String[sc.nextInt()];
        for (int i = 0;i < word.length;i++){
            word[i] = sc.next();
        }
        Arrays.sort(word);
        for (String temp:word){
            System.out.println(temp);
        }
    }
}

时间复杂度:O(nlogn)O(nlogn) sort函数的复杂度约是O(nlogn)O(nlogn)O(nlogn)。

空间复杂度:O(1)O(1) 不需要额外空间。