您的位置:首页 > 其它

1/20集训一 STL C. (set/map +string 找单词按字典序排列) Andy's First Dictionary

2018-01-21 08:27 686 查看

1/20集训一 STL

C. (set/map +string 找单词按字典序排列) Andy’s First Dictionary

Andy, 8, has a dream - he wants to produce his very own dictionary. This is not an easy task for

him, as the number of words that he knows is, well, not quite enough. Instead of thinking up all

the words himself, he has a briliant idea. From his bookshelf he would pick one of his favourite

story books, from which he would copy out all the distinct words. By arranging the words in

alphabetical order, he is done! Of course, it is a really time-consuming job, and this is where a

computer program is helpful. You are asked to write a program that lists all the different words in the input text. In this problem, a word is de ned as a consecutive sequence of alphabets, in upper and/or lower case.Words with only one letter are also to be considered. Furthermore, your program must be CaSe InSeNsItIvE. For example, words like \Apple”, \apple” or \APPLE” must be considered the same.

Input

The input le is a text with no more than 5000 lines. An input line has at most 200 characters. Input is terminated by EOF.

Output

Your output should give a list of different words that appears in the input text, one in a line. The

words should all be in lower case, sorted in alphabetical order. You can be sure that he number of distinct words in the text does not exceed 5000.

Sample Input

Adventures in Disneyland

Two blondes were going to Disneyland when they came to a fork in the

road. The sign read: “Disneyland Left.”

So they went home.

Sample Output

a

adventures

blondes

came

disneyland

fork

going

home

in

left

read

road

sign

so

the

they

to

two

went

were

when

题意:

根据一段给定的文本,找出所有不同的单词,并按照字典序排列输出。

思路:

不同单词,用map标记,然后直接输出即可,因为map就是按照字典序排列的。

#include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#define MAXN 10005
using namespace std;

string word;

int main()
{
map<string, int> ans;
char a;
int num = 0;
while(~(a = getchar()))
{
if(isalpha(a))
{
word += tolower(a);
}
else
{
if(ans[word]){
word="";
continue;
}
else
ans[word]=1;
word="";
}
}
for(auto &i:ans){
if(i.first!="")
cout<<i.first<<endl;
}
return 0;
}


提示:

这里用set更好,因为set中的元素就是不同的,同时,可以用streamstring处理单词。

#include<iostream>
#include<string>
#include<sstream>
#include<set>
#include<cctype>
usingnamespacestd;
set<string>se;
intmain()
{
strings;
while(cin>>s)
{
for(inti=0; i<s.length(); i++)
{
if(isalpha(s[i]))s[i]=tolower(s[i]);
elses[i]='';
}
stringstream ss(s);
string buf;
while(ss>>buf) se.insert(buf);
}
for(set<string>::iterator it=se.begin(); it!=se.end(); it++)
cout<<*it<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: