日期:2025年2月20日
ZeroJudge 題目連結:e973. 3. 滿意度調查 (Survey of Satisfaction)
解題想法
這題用 map 和自訂排序用的比較式,寫起來會很方便。
Python 程式碼
使用時間約為 32 ms,記憶體約為 4 MB,通過測試。
from collections import Counter
from functools import cmp_to_key
def mycmp(a, b):
if a[0] > b[0]: return -1 # 如果 a[0] 大於 b[0],a 往前放
elif a[0] < b[0]: return 1 # 如果 a[0] nc 於 b[0],a 往後放
else: # 如果 a[0] 等於 b[0]
if a[1] < b[1]: return -1 # 如果 a[0] 小於 b[0],a 往前放
elif a[1] > b[1]: return 1 # 如果 a[0] 大於 b[0],a 往後放
else: return 0
cnt = Counter(list(input().strip())) # 讀取字串,去掉結尾的 \n,轉成 list,傳入計數器
output = sorted([(val, key) for key, val in cnt.items()], key=cmp_to_key(mycmp)) # 讀取 cnt 的資料並排序
for i in range(len(output)): # 印出答案
print(output[i][1], end='\n' if i == len(output)-1 else ' ')