EOJ 3124 单词表

题目描述

提取英文文本中的单词,重复出现的单词只取一个,把它们按照字典顺序排序,建立为一个单词表。

例如:英文文本如下:

“ask not what your country can do for you,ask what you can do for your country.”

提取的非重复单词为:

ask not what your country can do for you

排序后建立的单词表为:

ask can country do for not what you your

注意:

(1) 单词与单词之间用空格或标点符号(逗号 (,),句号 (.), 惊叹号 (!), 问号 (?))分隔。

(2) 提取的单词只包含 26 个英文字符。

Input

第 1 行:一个整数 T (1≤T≤10) 为问题数。

接下来 T 行,每行输入一段文本,文本长度不超过 500 个字符。

文本由空格,逗号 (,),句号 (.), 惊叹号 (!), 问号 (?) 以及 26 个小写英文字符组成。
Output

对于每个问题,输出一行问题的编号(0 开始编号,格式:case #0: 等)。

然后对应每个问题 , 在一行中输出建立的单词表,单词与单词之间用一个空格分隔。最后一个单词后面没有空格。

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <set>
 4 #include <string>
 5 #include <sstream>
 6 using namespace std;
 7 int main()
 8 {
 9     int T,m=0;  scanf("%d
",&T);
10     while(T--)
11     {
12         printf("case #%d:
",m++);
13         string ss,tmp;
14         getline(cin,ss);
15         set <string> graph;
16         for(int i=0;i<ss.size();i++)
17             if(!isalpha(ss[i])) ss[i]=' ';
18         stringstream a(ss);
19 
20         while(a>>tmp)   graph.insert(tmp);
21 
22         set<string>::iterator it=graph.begin();
23         for(int j=0;j<graph.size()-1;j++,it++)
24             cout<<*it<<" ";
25         cout<<*it<<endl;
26     }
27     return 0;
28 }

显然是使用set嘛,至于如何把每个单词读入,看16,17行,将分隔符改成空格,然后用stringstream流,一个一个提取单词之后读入set中,set自动排序美滋滋。


stringstream的运行机制不明,有待学习。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     int t; string str, tmp;
 6     (cin >> t).get();
 7     for (int c = 0; c < t; c++)
 8     {
 9         getline(cin, str);
10         for (auto &i : str)
11             if (!isalpha(i))i = ' ';
12         stringstream ss(str);
13         set<string>ans;
14         while (ss >> tmp)ans.insert(tmp);
15         auto x = ans.begin();
16         cout << "case #" << c << ":
" << *x;
17         while (++x != ans.end())
18             cout << ' ' << *x;
19         cout << endl;
20     }
21 }

这个做法思路一样,不过更精简,得益于

 for (auto &i : str) 

以及在控制“最后一个不带空格”的条件上也处理的很好。

 #include<bits/stdc++.h> 到底是个啥玩意儿?



原文地址:https://www.cnblogs.com/Jiiiin/p/8589668.html