题目
字符串排序_牛客题霸_牛客网 (nowcoder.com)
C语言
#include <stdio.h>
#include <string.h>
void fun_2024_6_24(void)
{
int n;
scanf("%d", &n);
//在堆区申请内存
/*为什么不直接char p[n][101]? 因为n是变量,数组定义不可以,但是网上说有的编译器可以*/
char** p=(char**)malloc(n*sizeof(char *));
for (int _ = 0; _ < n; _++)
{
p[_] = (char *)malloc(101 * sizeof(char));
scanf("%s", p[_]);
//printf("%s\n",p[_]);
}
for (int i = 0; i < n; i++)
{
int flag = 0;
char tmp[101];
for (int j = i + 1; j < n; j++)
{
if (strcmp(p[i], p[j]) > 0)
{
strcpy(tmp,p[i]);
strcpy(p[i], p[j]);
strcpy(p[j], tmp);
}
flag = 1;
}
if (!flag) break;
}
for (int _ = 0; _ < n; _++)
printf("%s\n", p[_]);
//释放内存
for (int _ = 0; _ < n; _++)
{
free(p[_]);
p[_]=NULL;
}
if(!p)
{
free(p);
p=NULL;
}
}
int main()
{
fun_2024_6_24();
return 0;
}
C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void fun_2024_6_24(void)
{
vector<string> str_v;
string s;
int n;
cin >> n;
for (int _ = 0; _ < n; _++)
{
cin >> s;
str_v.push_back(s);
}
sort(str_v.begin(),str_v.end());
for (int _ = 0; _ < n; _++)
cout << str_v[_] << endl;
}
int main()
{
fun_2024_6_24();
return 0;
}
Python
n=int(input())
res=[]
for _ in range(n):
res.append(input())
res.sort()
for _ in res:
print(_)