日期:2026年4月26日
ZeroJudge 題目連結:d187. 11530 - SMS Typing
解題想法
這題可以用字典建表,先記錄每個字元對應的次數,讀取測資後再依序取出字元,計算次數加總。
Python 程式碼
使用時間約為 7 ms,記憶體約為 8.2 MB,通過測試。
table = {'a': 1, 'b': 2, 'c': 3,
'd': 1, 'e': 2, 'f': 3,
'g': 1, 'h': 2, 'i': 3,
'j': 1, 'k': 2, 'l': 3,
'm': 1, 'n': 2, 'o': 3,
'p': 1, 'q': 2, 'r': 3, 's': 4,
't': 1, 'u': 2, 'v': 3,
'w': 1, 'x': 2, 'y': 3, 'z': 4,
' ': 1}
n = int(input())
for i in range(1, n+1):
s = input()
cnt = sum(table[c] for c in s)
print(f"Case #{i:d}: {cnt:d}")
C++ 程式碼
使用時間約為 1 ms,記憶體約為 3.2 MB,通過測試。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
map<char, int> table =
{{'a', 1}, {'b', 2}, {'c', 3},
{'d', 1}, {'e', 2}, {'f', 3},
{'g', 1}, {'h', 2}, {'i', 3},
{'j', 1}, {'k', 2}, {'l', 3},
{'m', 1}, {'n', 2}, {'o', 3},
{'p', 1}, {'q', 2}, {'r', 3}, {'s', 4},
{'t', 1}, {'u', 2}, {'v', 3},
{'w', 1}, {'x', 2}, {'y', 3}, {'z', 4},
{' ', 1}};
int n; cin >> n; cin.ignore();
for(int i=1; i<=n; i++) {
string s; getline(cin, s);
int cnt = 0;
for(char c : s) cnt += table[c];
cout << "Case #" << i << ": " << cnt << "\n";
}
return 0;
}
沒有留言:
張貼留言