iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
自我挑戰組

cpe30天練習系列 第 22

cpe練習day22

  • 分享至 

  • xImage
  •  

今天是練習cpe的Tell me the frequencies題目

程式碼

#include <bits/stdc++.h>
#define p pair<int,int> 
using namespace std;
bool cmp(p a, p b)
{ 
	if (a.first != b.first) 
	{
		return a.first < b.first;
	}
	else 
	{
		return a.second > b.second; 
	}
} 

int main() 
{ 
 	string s; 
	while (getline(cin, s)) 
	{ 
		p a[256]; 
		for (int i = 0; i < 256; i++) 
		{ 
			a[i] = {0, i}; 
		} 
		for (int i = 0; i < s.length(); i++) 
		{ 
			a[(int)s[i]].first++; 
		} 
		sort(a, a+256, cmp); 
		for (auto i: a)
		{ 
			if (i.first > 0) 
			{ 
				cout << i.second << " " << i.first << endl ; 
			} 
		} 
		cout << endl ; 
	} 
	return 0; 
}

解題方向

  • #define p pair<int,int> -> 宣告一個型別別名p等同於pair<int,int>,用來存(次數, ASCII值)
  • bool cmp(p a, p b) -> 這是自訂的比較函式,用來給 sort()排序時使用,a.first是出現次數,a.second是ASCII值先比出現次數,次數少的排前面如果次數相同,就比ASCII值,ASCII大的排前面
  • a[i].first = 0 -> 初始次數 0
  • a[i].second = i -> 記錄 ASCII 值
  • a[(int)s[i]].first++; -> 對字串中每個字元s[i],找到對應的ASCII值,出現次數+1
  • sort(a, a+256, cmp); -> 依照剛剛定義的cmp()排序,出現次數少的排前面,若相同就比ASCII值,ASCII 大的排前面

上一篇
cpe練習day21
系列文
cpe30天練習22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言