统计字符串中出现最多的单词和次多的单词
2013-09-09 19:05
931 查看
题目:统计字符串中出现最多的单词和次多的单词。
测试用例:"This This This a dog,not a cat!"
输出:This 3次 a 2次
思路:先把这个字符串分词,放入一个数组中。然后记录每个词出现的次数。先找出最多的那个词,然后将其次数置0,在找最多的那个词(原来次多的词)。
测试用例:"This This This a dog,not a cat!"
输出:This 3次 a 2次
思路:先把这个字符串分词,放入一个数组中。然后记录每个词出现的次数。先找出最多的那个词,然后将其次数置0,在找最多的那个词(原来次多的词)。
#include<iostream> using namespace std; #define MAX_COUNT_WORD 256 bool isCounted[MAX_COUNT_WORD];//标记该单词已经统计过,即是否在前面出现过 int times[MAX_COUNT_WORD]; //统计单词次数 //判断是否为符合单词的字符 bool isRightChar(char data) { return data>='a'&&data<='z'||data>='A'&&data<='Z'; } //判断是否为相同的字符串 bool isSameStr(const char* first,const char* second) { if(strlen(first)!=strlen(second)) return false; while(*first++!=*second++) return false; return true; } void main() { char* data="This This This a dog,not a cat!"; int length=strlen(data); int i; //统计单词个数和最大长度 int count=0; int lastindex=-1; int currentindex=-1; int maxLength=0; for(i=0;i<length;++i) { currentindex=i; if(!isRightChar(data[i])) { if(currentindex-lastindex>1) { ++count; if(currentindex-lastindex-1>maxLength) maxLength=currentindex-lastindex-1; } lastindex=currentindex; } } //分词 char** word=new char*[count]; for(i=0;i<count;++i) { word[i]=new char[maxLength+1]; memset(word[i],0,maxLength+1); } int current_count=0; lastindex=-1; currentindex=-1; for(i=0;i<length;i++) { currentindex=i; if(!isRightChar(data[i])) { if(currentindex-lastindex>1) { memcpy(word[current_count++],data+lastindex+1,currentindex-lastindex-1); } lastindex=currentindex; } } //比较字符串,统计次数 int j; int temp_count=1; for(i=0;i<count;++i) { if(isCounted[i]) continue; for(j=i+1;j<count;++j) { if(isSameStr(word[i],word[j])) { isCounted[j]=true; temp_count++; } } times[i]=temp_count; temp_count=1; isCounted[i]=true; } //统计最多的次数 单词 int max_times=0; int indexOfWord=0; for(i=0;i<count;++i) { if(times[i]&×[i]>max_times) { max_times=times[i]; indexOfWord=i; } } times[indexOfWord]=0; cout<<"最多的单词次数为: "<<max_times<<" 它是: "<<word[indexOfWord]<<endl; //统计次多的次数 单词 max_times=0; indexOfWord=0; for(i=0;i<count;++i) { if(times[i]&×[i]>max_times) { max_times=times[i]; indexOfWord=i; } } cout<<"次多的单词次数为: "<<max_times<<" 它是: "<<word[indexOfWord]<<endl; }
相关文章推荐
- 统计字符串中出现最多的单词和次多的单词
- 统计一串字符串中出现次数最多和次多的单词
- 华为:统计一串字符串中出现次数最多和次多的单词(华为上机考试题)
- 统计一串字符串中出现次数最多和次多的单词(华为上机考试题)
- 统计一串字符串中出现次数最多和次多的单词(华为上机考试题)
- 统计字符串中每个单词出现的次数 for C++
- OC 找出在只有空格字母的字符串中出现次数最多的单词
- 用C语言实现了对英文文章中单词频率的统计,得到出现最多的前十个!
- 统计字符串中出现次数最多的字母的次数,如果有多个重复的,都求出
- 判断一个字符串中出现次数最多的字符,并统计这个次数
- 找出并统计任意字符串中出现最多的字符
- JS实现找到某字符串中出现次数最多的字符,并统计次数
- Python 练习册 6-统计文本文件中的出现最多的单词
- JAVA-统计英文句子中出现次数最多的单词和出现的次数
- 微软笔试题 统计英文电子书中出现次数最多的k个单词
- 统计一组字符串中各个单词出现的次数
- java统计字符串中出现最多的字符
- 编写函数 void count(char a[],char w[][10],int n,int b[]).功能是:统计w指向的数组中的n个单词在a指向的字符串中各自出现的次数(将非字符字符看作单词分割
- 判断一个字符串中出现次数最多的字符,统计这个次数
- C# 实现统计字符串中不同单词的出现次数【百度笔试题】