描述
        给定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

方法一:单词排序
核心思想:
        用vector容器接收单词,然后使用自带的sort方法排序单词

核心代码:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

void sort_words(vector<string> words,int n){
    sort(words.begin(),words.end());
    for(int i=0;i<n;i++)
        cout<<words[i]<<endl;
}

int main(){
    int i,n;
    cin>>n;
    vector<string> words(n);
    for(i=0;i<n;i++)
        cin>>words[i];
    sort_words(words,n);
    return 0;
}

时间复杂度O(NlogN)
空间复杂度O(N)
复杂度说明:sort排序使用的是内置函数,时间复杂度为O(N
logN),,因此时间复杂度为O(N*logN),由于程序使用了vector容器临时存储n个元素,因此空间复杂度为O(N)


方法二:使用multiset自动排序
核心思想:
        将控制台输入的字符串保存到multiset数据结构中,然后迭代输出multiset

核心代码:

#include<iostream>
#include<string>
#include<set>
#include<algorithm>
using namespace std;

void sort_words(multiset<string> words,int n){
     for (multiset<string>::iterator it=words.begin();it!=words.end();++it)
        cout << *it<<endl;
}

int main(){
    int i,n;
    cin>>n;
    multiset<string> words;     //使用multiset,会自动排序字符串
    string s;
    for(i=0;i<n;i++){
        cin>>s;
        words.insert(s);
    }
    sort_words(words,n);
    
    return 0;
}

时间复杂度O(NlogN)
空间复杂度O(N)
复杂度说明:multiset内置函数的增删改查时间复杂度为O(logN),外层循环N次,因此总的时间复杂度为O(N
logN),由于程序使用了multiset容器临时存储n个元素,因此空间复杂度为O(N)