简单的统计英文单词个数

给出一篇英文文章,现在需要统计文章中出现英文单词的数量。

输入格式:

第一行一个T,代表数据组数 对于每组数据,第一行一个n,代表文章中单词的个数,其后n行每行一个只包含小写字母的长度为1到10的字符串

输出格式:

每组数据输出若干行,每行输出单词以及它出现的次数(中间空格隔开),不同单词按单词字典序从小到大输出 保证单词出现的总次数<=1e5

输入样例:

1
8
it
is
a
pen
it
is
a
dog

输出样例:

a 2
dog 1
is 2
it 2
pen 1

c++的代码,使用map来做:

#include <iostream>
#include <map>
#include <iterator>
#include <stdlib.h>
using namespace std;

main()
{
          
   
 typedef map<string,long >word;
  int len, n,num=0 ;
 word pairs;  
 long k = 1;
 cin>>n;
 while(num < n)
 {
          
   
  cin>>len;
  string *f = new string [len];
  for(int i=0;i<len;i++)
     {
          
   
      cin>>f[i];
      if(pairs.count(f[i]) == 0)
      {
          
   
    pairs.insert(make_pair(f[i],k));
     }else{
          
   
    pairs[f[i]] ++;
   }
      
  }
  word::iterator j;
  for(j = pairs.begin(); j!= pairs.end(); j++)
   cout<<j->first<<" "<<j->second <<endl;
//  cout<<endl; 
  pairs.clear();
  num++;
  }
 return 0;
}

运行没问题的

#include<bits/stdc++.h>
using namespace std;
typedef map<string,long >word;

main()
{
          
   
 word M;
 int tt,n; 
 string s;
 ios::sync_with_stdio(0);
 cin>>tt;
 while(tt--)
 {
          
   
  cin>>n;
  M.clear();
  for(int i=0;i<n;++i)
  {
          
   
   cin>>s;
   ++M[s];	//给s的值++
  }
  word::iterator j;
  for(j = M.begin(); j!= M.end(); j++)
   cout<<j->first<<" "<<j->second <<endl;
 }
 return 0;
}
经验分享 程序员 微信小程序 职场和发展