单词统计(华为测试题目)
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;
}
相关文章推荐
- Android之使用Http协议实现文件上传功能
- mysql集群之MMM简单搭建
- 通晓网络测试常用命令
- 华为路由器密码恢复
- 华为交换机的后缀详解
- Nodejs学习笔记之测试驱动
- 自动化测试读写64位操作系统的注册表
- 可以测试javascript运行效果的代码
- 使用php测试硬盘写入速度示例
- python 测试实现方法
- 如何测试端口通不通(四种方法)
- 举例详解PHP脚本的测试方法
- 使用Jasmine和Karma对AngularJS页面程序进行测试
- Php-Redis安装测试笔记
- mysql压力测试脚本实例
- JavaScript 组件之旅(四):测试 JavaScript 组件
- js简单网速测试方法完整实例
- Android App开发的自动化测试框架UI Automator使用教程
- Android触屏测试实例代码
- 解析libcurl在android下的移植、编译与测试