【华为机试】字串的连接最长路径查找

时间:2022-01-28 13:14:51

题目描述

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

输入描述:

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

输出描述:

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

方法一分析:用插入法进行排序,注意要用到getchar()消除回车;

#include <iostream>
#include <vector>
#include <string>
using namespace std;
//插入排序;
int main(){
int n;
while (cin >> n){
vector<string> res;
string s;
getchar();//用getchar()消除回车缓存;
while (n--){ //插入排序;
getline(cin,s);
if (res.empty()) res.push_back(s);
else {
int i = 0;
while (i < res.size()){
if (s < res[i]){
res.insert(res.begin() + i, s); break;
}
i++;
}
if (i == res.size()) res.push_back(s);
}
}
int i = 0; cout << endl;
while (i < res.size()) cout << res[i++] << endl;
}
return 0;
}

方法二分析:用algorithm库中的sort()方法进行排序,很方便;

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

bool strcom(string a, string b){ //参数类型为容器元素类型,自己用的少;
return a < b;
}

int main(){
int n;
while (cin >> n){
getchar();//用getchar()消除回车缓存;
string s;
vector<string> res;
while (n--&&getline(cin,s)){
res.push_back(s);
}
sort(res.begin(), res.end(),strcom);
for (int i = 0; i < res.size(); i++)
cout << res[i] << endl;
}
return 0;
}