一、题目
描述
给定 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行,输出结果为按照字典序排列的字符串。
示例1
输入:
9
cap
to
cat
card
two
too
up
boat
boot输出:
boat
boot
cap
card
cat
to
too
two
up
二、C语言解法
#include "stdio.h"
#include "string.h"int main() {int num = 0, i = 0, j = 0;char s[1000][101];char tmp[101];scanf("%d", &num);for (i = 0; i < num; i++) {scanf("%s", s[num - i - 1]);}for (j = num - 1; j > 0; j--) {for (i = 0; i < j; i++) {if (strcmp(s[i], s[i + 1]) > 0) {strcpy(tmp, s[i + 1]);strcpy(s[i + 1], s[i]);strcpy(s[i], tmp);}}}for (i = 0; i < num; i++) {printf("%s\n", s[i]);}return 0;
}
知识点:
strcmp(str1, str2)函数用于比较两个字符串并根据比较结果返回整数。若str1=str2,则返回零;若str1>str2,则返回正数;若str1<str2,则返回负数。(个人理解可以用减法str1-str2帮助记忆)。
三、python解法
while True:try:num=int(input()) #输入numstack=[] for i in range(num):stack.append(input()) #向列表尾部添加字符串print("\n".join(sorted(stack)))except:break
知识点:
stack.append:在列表尾部添加新的元素。
"\n".join() :str.join(sequence),join方法用于链接字符串序列,str表示分隔符,sequence表示需要连接的字符串序列。
sorted(stack):将列表stack以默认从小到大排序。