洛谷P1308 统计单词数
2018-02-19 19:40
183 查看
题目简介
题目描述一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。
现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例1 ),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例2 )。
输入输出格式
输入格式:
输入文件名为stat.in ,2 行。
第1 行为一个字符串,其中只含字母,表示给定单词;
第2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。
输出格式:
输出文件名为stat.out 。
只有一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从 0 开始);如果单词在文章中没有出现,则直接输出一个整数-1。
输入输出样例
输入样例#1:
To
to be or not to be is a question
输出样例#1:
2 0
输入样例#2:
to
Did the Ottoman Empire lose its power at that time
输出样例#2:
-1
思路
如果直接暴力扫的话,最后的样例会超时,所以最好的解决方案是采用STL的函数,效率较高。C++代码样例
#include <cstdio> #include <cstdlib> #include <string> #include <iostream> #include <functional> #include <algorithm> using namespace std; int main(void) { int count = 1, firstpos = 0, nextpos = 0; string target = ""; string source = ""; getline(cin, target); getline(cin, source); target = " " + target + " "; source = " " + source + " "; transform(target.begin(), target.end(), target.begin(), (int(*)(int))std::tolower); transform(source.begin(), source.end(), source.begin(), (int(*)(int))std::tolower); if(source.find(target) == string::npos) { cout << "-1" << endl; return 0; } else { firstpos = source.find(target); nextpos = firstpos; nextpos = source.find(target, nextpos + 1); while(nextpos != string::npos) { count++; nextpos = source.find(target, nextpos + 1); } } cout << count << " " << firstpos; return 0; }
相关文章推荐
- 洛谷P1308 统计单词数
- 洛谷P1308 统计单词数
- 洛谷P1308 统计单词数
- 用array_count_values统计一篇英文文档中每个单词的出现次数,结果用表格展示出来
- Linux命令温故而知新:统计行数,单词,字符数
- C语言统计输入行数、单词数、字符数
- spark on yarn运行scala单词统计程序出错
- map下统计单词出现的地方
- MapReduce进行本地的单词统计
- Problem F: 统计单词数
- Hive mapreduce SQL实现原理——SQL最终分解为MR任务,而group by在MR里和单词统计MR没有区别了
- grep统计某个单词的个数
- 打开文件并统计以空格隔开的单词数目
- 洛谷 P1026 统计单词个数
- 关于统计ascii码文本中英语单词的出现频率的c++实现
- linux中sort(统计文件中出现次数最多的前10个单词)
- 统计出现频率最高的十个单词的程序性能分析
- textarea实时统计输入单词个数
- 统计文件中出现次数最多的前10个单词
- java统计一个文件的字符数,单词数,行数