首页 › 题库 › C/C++编程考级 › C/C++编程二级 › 简答题
简答题 偏难
#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 &lt;bits/stdc++.h&gt; using namespace std; string s[105],x; int main() { int i=0; while(cin&gt;&gt;x){ s[i++]=x; } sort(s,s+i); cout&lt;&lt;s[0]&lt;&lt;endl; for(int j=1;j&lt;i;j++){ if(s[j]!=s[j-1]) cout&lt;&lt;s[j]&lt;&lt;endl; }     return 0; }</pre><pre class="brush:cpp;toolbar:false">// C++参考代码2 #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;set&gt; #include &lt;string&gt; int main() {     std::string input;     std::getline(std::cin, input);  // 读取一行输入          std::set&lt;std::string&gt; words;  // 使用集合存储单词,确保输出时没有重复的单词          std::stringstream ss(input);  // 使用字符串流处理输入          std::string word;     while (ss &gt;&gt; word) {         words.insert(word);  // 将单词插入集合中     }          // 遍历集合,按字典序输出单词     for (const std::string&amp; w : words) {         std::cout &lt;&lt; w &lt;&lt; std::endl;     }          return 0; }</pre><pre class="brush:cpp;toolbar:false">// C语言参考代码 #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; // 比较函数,用于排序 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 &lt; num_words; i++) {         int is_duplicate = 0;         for (int j = 0; j &lt; 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 &lt; unique_count; i++) {         printf("%s\n", unique_words[i]);     }          return 0; }</pre>
这道题暂未补解析。