微软笔试题 统计英文电子书中出现次数最多的k个单词

来源:互联网 发布:ubuntu 16.04应用商店 编辑:程序博客网 时间:2024/04/30 02:55

        在v_JULY_v的文章中找到了这个问题的解法后用C++实现了一下,发现C++的代码非常的简洁。

主要用到了标准库中的hash_map,优先级队列priority_queue。

        算法的思路是:

  1. 从头到尾遍历文件,从文件中读取遍历到的每一个单词。
  2. 把遍历到的单词放到hash_map中,并统计这个单词出现的次数。
  3. 遍历hash_map,将遍历到的单词的出现次数放到优先级队列中。
  4. 当优先级队列的元素个数超过k个时就把元素级别最低的那个元素从队列中取出,这样始终保持队列的元素是k个。
  5. 遍历完hash_map,则队列中就剩下了出现次数最多的那k个元素。

      具体实现和结果如下:

//出现次数最多的是个单词

[cpp] view plaincopy
  1. //出现次数最多的是个单词  
  2. void top_k_words()  
  3. {  
  4.     timer t;  
  5.     ifstream fin;  
  6.     fin.open("modern c.txt");  
  7.     if (!fin)  
  8.     {  
  9.         cout<<"can nont open file"<<endl;  
  10.     }  
  11.     string s;  
  12.     hash_map<string,int> countwords;  
  13.     while (true)  
  14.     {  
  15.         fin>>s;  
  16.         if (fin.eof())  
  17.         {  
  18.             break;  
  19.         }  
  20.         countwords[s]++;  
  21.     }  
  22.     cout<<"单词总数 (重复的不计数):"<<countwords.size()<<endl;  
  23.     priority_queue<pair<int,string>,vector<pair<int,string>>,greater<pair<int,string>>> countmax;  
  24.     for(hash_map<string,int>::const_iterator i=countwords.begin();  
  25.         i!=countwords.end();i++)  
  26.     {  
  27.         countmax.push(make_pair(i->second,i->first));  
  28.         if (countmax.size()>10)  
  29.         {  
  30.             countmax.pop();  
  31.         }  
  32.     }  
  33.     while(!countmax.empty())  
  34.     {  
  35.         cout<<countmax.top().second<<" "<<countmax.top().first<<endl;  
  36.         countmax.pop();  
  37.     }  
  38.     cout<<"time elapsed "<<t.elapsed()<<endl;  
  39. }  



 

0 0
原创粉丝点击