第一行给出单词数 n,接下来 n 行每行一个单词,单词只由小写英文字母组成。 第一行把单词按输入的相反顺序输出,用一个空格分隔;第二行输出最长的单词。 如果有多个同样最长的单词,输出在输入中最先出现的那个。 n 要运行时才知道,所以试着不用固定大小的数组,而是把所有单词存进运行时申请的内存里来解(C 用 malloc、free,C++ 用 std::vector 和 std::string)。
输入
1 ≤ n ≤ 2,000,单词长度在 1 到 100 之间
输出
两行:倒序排列的单词,最长的单词
样例 1 · stdin
4
hi
hello
hey
howdy
stdout
howdy hey hello hi
hello
main.py
错误列表00F8 ↓ · ⇧F8 ↑
输入(stdin)
运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。
$ 就绪
请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。
其他语言怎么写?查看各语言题解 · 2 种语言题解
这道题只接受 C 和 C++。 亲手申请和归还内存是这两种语言的事,Python、JavaScript、TypeScript、Java、C# 和 Craykon 的列表会自己变长,垃圾回收器会清理,所以不用写。 C 要申请两次:指向单词的指针格子 char **words = malloc(n * sizeof *words),以及每个单词复制到 malloc(strlen(buf) + 1) 里(+1 是结尾 '\0' 的位置)。 用完后先逐个 free 单词,再 free(words),申请多少就恰好归还一次。 C++ 由 std::vector<std::string> 负责申请和归还(RAII)。 两个陷阱:① 在 C 里像 scanf("%100s", buf); words[i] = buf; 这样不复制只存地址,所有格子都指向同一个 buf,全都显示为最后一个单词,而且不报错。 ② 在 C++ 里 std::vector<std::string> words(n); 已经装着 n 个空字符串,再 push_back 会接在它们后面,大小变成 2n。 只想预留空间就用 reserve(n) 再 push_back,否则用 words(n) 再 words[i] = w。
C++main.cpp · 26 行
#include <iostream>#include <string>#include <vector>int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; // vector와 string이 알아서 힙 메모리를 빌리고, 범위를 벗어나면 돌려준다(RAII) std::vector<std::string> words; words.reserve(n); // 칸을 미리 잡아 둘 뿐, 크기(size)는 아직 0 for (int i = 0; i < n; i++) { std::string w; std::cin >> w; words.push_back(w); // string은 대입·push_back 때 글자를 복사해 둔다 } for (int i = n - 1; i >= 0; i--) std::cout << words[i] << (i > 0 ? ' ' : '\n'); const std::string* best = &words[0]; for (const auto& w : words) if (w.size() > best->size()) best = &w; std::cout << *best << "\n";}
Cmain.c · 33 行
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) { int n; scanf("%d", &n); /* 낱말 수는 실행해 봐야 안다: 낱말을 가리킬 포인터 n칸을 힙에서 빌린다 */ char **words = malloc(n * sizeof *words); if (words == NULL) return 1; char buf[101]; /* 읽기용 칸은 하나뿐이라, 낱말마다 따로 복사해 둬야 한다 */ for (int i = 0; i < n; i++) { scanf("%100s", buf); size_t len = strlen(buf); words[i] = malloc(len + 1); /* +1은 끝을 알리는 '\0' 자리 */ if (words[i] == NULL) return 1; memcpy(words[i], buf, len + 1); } for (int i = n - 1; i >= 0; i--) printf("%s%c", words[i], i > 0 ? ' ' : '\n'); const char *best = words[0]; for (int i = 1; i < n; i++) if (strlen(words[i]) > strlen(best)) best = words[i]; printf("%s\n", best); /* 빌린 것은 빌린 만큼 돌려준다: 낱말 하나하나, 그다음 포인터 칸 */ for (int i = 0; i < n; i++) free(words[i]); free(words); return 0;}