单词问题
欢迎进入我的C语言世界
题目
Problem Description
给出一个完整的句子,这个句子中不包含不可见字符或者空格,于是在这个句子中有许多不同的单词。一个单词是指一串连续的最长的英文字母(大写或小写)。例如"#abc#"中,“abc"就是一个单词,而"ab”,"bc"都不算单词。
Input
输入包含多组数据 输入数据第一行是一个句子,只包含可见字符(不包含空格)。句子长度不超过 100。
Output
按单词出现的顺序输出不同的单词。如果一个单词出现多次则只有第一次出现时输出。
Sample Input
Orz_YaYaMao_Orz_Daxia_Orz_EveryOne
Sample Output
Orz
YaYaMao
Daxia
EveryOne
答案
下面展示 实现代码
。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <map>
char a[107], b[107];
using namespace std;
int main()
{
map<string, int>m;
map<string, int>::iterator it;
while(scanf("%s",a) != EOF)
{
int len = strlen(a);
int j = 0;
for(int i = 0; i <= len; i++)
{
if((a[i] >= 'a' && a[i] <= 'z')||(a[i] >= 'A' && a[i] <= 'Z'))
{
b[j] = a[i];
j++;
}
else if(j > 0)
{
b[j] != '\0';
it = m.find(b);
if(it == m.end())
{
m.insert(map<string,int>::value_type(b,1));
printf("%s\n",b);
}
j = 0;
memset(b,0,sizeof(b));
}
}
m.clear();
}
return 0;
}
下面展示 WA代码
。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <map>
char a[107], b[107];
using namespace std;
int main()
{
map<string, int>m;
map<string, int>::iterator it;
while(scanf("%s",a) != EOF)
{
int len = strlen(a);
int j = 0;
for(int i = 0; i <= len; i++)
{
if((a[i] >= 'a' && a[i] <= 'z')||(a[i] >= 'A' && a[i] <= 'Z'))
{
b[j] = a[i];
j++;
}
else if(j > 0)
{
b[j] != '\0';
it = m.find(b);
if(it == m.end())
{
m.insert(map<string,int>::value_type(b,1));
printf("%s\n",b);
}
j = 0;
memset(b,0,sizeof(b));
}
}
m.clear();
}
return 0;
}
本题感悟
本块内容可能来自课本或其他网站,若涉及侵权问题,请联系我进行删除,谢谢大家啦~
- 学习了一点map,WA的做法提供了一个思路,但是不能实现按输入顺序输出,听说vector和list可以,这里先做个记录
- 实现的代码也是一个很好的思路
以上。