简答题
偏难
#7410
单词排序(2023.12) 输入一行单词序列,相邻单词之间由 1 个或多个空格间隔,请按照字典序输出这些单词,要求重复的单词只输出一次。(区分大小写) 输入 一…
单词排序(2023.12)
输入一行单词序列,相邻单词之间由 1 个或多个空格间隔,请按照字典序输出这些单词,要求重复的单词只输出一次。(区分大小写)
输入
一行单词序列,最少 1 个单词,最多 100 个单词,每个单词长度不超过 50,单词之间用至少 1 个空格间隔。数据不含除字母、空格外的其他字符。
输出
按字典序输出这些单词,重复的单词只输出一次。
输入样例
She wants to go to Peking University to study Chinese
输出样例
Chinese Peking She University go study to wants
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">// C++参考代码1
#include <bits/stdc++.h>
using namespace std;
string s[105],x;
int main()
{
int i=0;
while(cin>>x){
s[i++]=x;
}
sort(s,s+i);
cout<<s[0]<<endl;
for(int j=1;j<i;j++){
if(s[j]!=s[j-1])
cout<<s[j]<<endl;
}
return 0;
}</pre><pre class="brush:cpp;toolbar:false">// C++参考代码2
#include <iostream>
#include <sstream>
#include <set>
#include <string>
int main() {
std::string input;
std::getline(std::cin, input); // 读取一行输入
std::set<std::string> words; // 使用集合存储单词,确保输出时没有重复的单词
std::stringstream ss(input); // 使用字符串流处理输入
std::string word;
while (ss >> word) {
words.insert(word); // 将单词插入集合中
}
// 遍历集合,按字典序输出单词
for (const std::string& w : words) {
std::cout << w << std::endl;
}
return 0;
}</pre><pre class="brush:cpp;toolbar:false">// C语言参考代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 比较函数,用于排序
int compare(const void* a, const void* b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main() {
char words[100][50];
char* unique_words[100];
int num_words = 0;
// 读取输入的单词序列
char input[10000];
fgets(input, sizeof(input), stdin);
// 解析单词
char* token = strtok(input, " ");
while (token != NULL) {
strcpy(words[num_words], token);
num_words++;
token = strtok(NULL, " ");
}
// 去除重复单词,保存到unique_words数组
int unique_count = 0;
for (int i = 0; i < num_words; i++) {
int is_duplicate = 0;
for (int j = 0; j < unique_count; j++) {
if (strcmp(words[i], unique_words[j]) == 0) {
is_duplicate = 1;
break;
}
}
if (!is_duplicate) {
unique_words[unique_count] = words[i];
unique_count++;
}
}
// 按字典序排序
qsort(unique_words, unique_count, sizeof(char*), compare);
// 输出结果
for (int i = 0; i < unique_count; i++) {
printf("%s\n", unique_words[i]);
}
return 0;
}</pre>
这道题暂未补解析。