您的位置:首页 > 其它

单词统计(华为测试题目)

2016-08-17 20:45 465 查看
单词统计
描述:输入一段英文文本,用程序统计出现频率最高和最低的两个单词:

1、英文文本中仅出现这四类字符:空格( )、英文逗号(,)、英文句号(.)、英文大小写字母(a-z、A-Z) 

2、单词之间的分隔符仅考虑这三种:空格( )、英文逗号(,)、英文句号(.); 

3、仅大小写不同的单词算同一个单词; 

4、如果两个单词出现次数相同,则在文本中首次出现的单词优先返回。 

5、输出的单词统一用小写字母返回。 

例如: 

输入字符串“Hello world, i said hello world to the world”,输出“world”,“i” 

输入字符串“Somebody like somebody,i do not like it”,输出“somebody”,“i”。

 
运行时间限制:无限制
内存限制:无限制
输入:一行字符串,长度小于1024,单词个数小于300个,如:Hello world, i said hello world to the world

 

 
输出:字符串,如:world,i 
样例输入:
Hello world, i said hello world to the world

样例输出:
world,i

分析:先将所有字母转为小写,然后记录单词并统计词频,最后遍历单词容器得到第一次出现并且词频最大或者最小的单词,输出。

以下是代码(有些边界条件没考虑,因为默认输出肯定有一个单词):

#include <iostream>

#include <string>

#include <map>

#include <vector>

using namespace std;

int main()

{
string str;
while (getline(cin, str))
{
vector<string> words;//定义单词容器存放每一个单词
map<string, int> wordsFreq;//定义词频统计

int strLen = str.length();//得到字符串长度

//为方便统计,字母全部转换为小写
for (int i = 0; i < strLen; ++i)
{
if ((str[i] >= 'A') && (str[i] <= 'Z'))
{
str[i] = str[i] + 32;
}
}

//统计词频
for (int i = 0; i < strLen; ++i)
{
string temp = "";
while ((str[i] >= 'a') && (str[i] <= 'z'))
{
temp += str[i];
++i;
}

//如果有单词,则记录
if (!temp.empty())
{
//记录单词
words.push_back(temp);

//统计词频
if (wordsFreq.find(temp) != wordsFreq.end())
{
++wordsFreq[temp];
}
else
wordsFreq[temp] = 1;

}
}

//得到词频最大和最少的两个单词
string wordMore = words[0];
int countWordMoreFreq = wordsFreq[wordMore];
string wordLess = words[0];
int countWordLessFreq = wordsFreq[wordLess];

int wordsSize = words.size();
for (int i = 1; i < wordsSize; ++i)
{
string temp = words[i];
if (wordsFreq[temp] > countWordMoreFreq)
{
wordMore = temp;
countWordMoreFreq = wordsFreq[temp];

else if (wordsFreq[temp] < countWordLessFreq)
{
wordLess = temp;
countWordLessFreq = wordsFreq[temp];
}
}

//输出
cout << wordMore << "," << wordLess << endl;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  华为 测试 单词统计