天天看點

OpenJudge-NOI/1.13程式設計基礎之綜合應用-29:統計字元數

29:統計字元數

總時間限制:1000ms 記憶體限制:65536kB

描述

給定一個由a-z這26個字元組成的字元串,統計其中哪個字元出現的次數最多。

輸入

輸入包含一行,一個字元串,長度不超過1000。

輸出

輸出一行,包括出現次數最多的字元和該字元出現的次數,中間以一個空格分開。如果有多個字元出現的次數相同且最多,那麼輸出ascii碼最小的那一個字元。

樣例輸入

abbccc

樣例輸出

c 3

這道題目和我寫的上一篇部落格采用的思想基本一緻,連結如下:

衆數(哈爾濱工業大學)

方法一:雙數組法

代碼如下:

#include<iostream>
#include<cstring>
using namespace std;
#define num 1001
char s[num];
int a[150];
int main()
{
 	int max=0,max_n=0;
 	cin >> s;
 	int len=strlen(s);
 	for(int i=0; i<len; ++i)
 	{
  		a[s[i]]++;
 	}
 	for(int i=97; i<123; ++i)
 	{
 		 if(a[i]>max)
  		{
   			max=a[i];
   			max_n=i;
  		}
 	}
 	cout << (char)max_n << " " << max;
	return 0;
}
//29:統計字元數 
//a-z的ASCII碼:97-122  
           

方法二:map大法

代碼如下:

#include<iostream>
#include<map>
#include<cstring>
using namespace std;
#define num 1001
char s[num];
map <char,int> ace;
int main()
{
 	cin >> s;
 	int len=strlen(s);
 	for(int i=0; i<len; ++i)
  		++ace[s[i]];
 	int maxn=0;
 	char a;
 	for(map <char,int>::iterator i=ace.begin(); 
 	i!=ace.end(); ++i)
 	{
  		if(i->second>maxn)
  		{
   			maxn=i->second;
  			a=i->first;
  		}
 	}
 	cout << a << " " << maxn;
 	return 0;
}
//29:統計字元數 
//map <key,value> 鍵值對  
//當 map内元素值為 int類型時,預設值為 0 
//map的預設排序規則是按照 key從小到大進行排序 即 a.key < b.key 為 true則 a排在 b 前面 
           

方法三:map和set合用

代碼如下:

#include<bits/stdc++.h>
using namespace std;
#define num 1001
char s[num];
struct Str
{
 	int times;
 	char ch;
};
struct Rule 
{
 	bool operator () ( const Str & s1,const Str & s2) const 
 	{
  		if(s1.times != s2.times)
   			return s1.times > s2.times;
 		 else
   			return s1.ch < s2.ch;
 	}
};
int main()
{
 	set<Str,Rule> st;
 	map<char,int> mp;
 	cin >> s;
 	int len = strlen(s);
 	for(int i=0; i<len; ++i)
  		++mp[s[i]];
 	for(map<char,int>::iterator i=mp.begin(); 
 	i!=mp.end(); ++i)
 	{
  		Str tmp;
  		tmp.ch=i->first;
  		tmp.times=i->second;
  		st.insert(tmp);
 	}
 	set<Str,Rule>::iterator i=st.begin();
 	cout << i->ch << " " << i->times;
 	return 0;
}
//29:統計字元數 
           

感謝觀看!

OpenJudge-NOI/1.13程式設計基礎之綜合應用-29:統計字元數

I’m coming home,Ace!